JPA #ManyToOne fields are empty - sql

I have spent hours looking how to solve this. When I try to get parent from a child all but it's id fields are empty. It just makes no sense. I am using PlayFramework 2.0.4 if that might indicate anything (besides a terrible choice of framework).
TRoute.java (parent)
#Entity
#Table(name="routes")
public class TRoute extends Model {
#Id
public String route_id;
public String agency_id;
#Constraints.Required
public String route_short_name;
#Constraints.Required
public String route_long_name;
public String route_desc;
#Constraints.Required
public String route_type;
public String route_url;
public String route_color;
public String route_text_color;
#OneToMany(mappedBy="troute")
public List<Trip> trips;
public static Finder<String, TRoute> find = new Finder(
String.class, TRoute.class
);
}
Trip.java (child)
#Entity
#Table(name="trips")
public class Trip extends Model {
#Constraints.Required
public String route_id;
#Constraints.Required
public String service_id;
#Id
public String trip_id;
public String trip_headsign;
public String direction_id;
public String block_id;
public String shape_id;
#ManyToOne
#JoinColumn(name="route_id")
public TRoute troute;
public static List<Trip> byRouteId(String route_id) {
List<Trip> trips =
Trip.find
.where().like("route_id", route_id)
.findList();
return trips;
}
public static Finder<String, Trip> find = new Finder(
String.class, Trip.class
);
}

The finder has a fetch() method which can be used to load properties of the other table. Something like:
public static List<Trip> byRouteId(String route_id) {
List<Trip> trips = List<Trip> trips = Trip.find
.fetch("troute") // fetch the other table's properties here
.where()
.like("route_id", route_id)
.findList();
return trips;
}

Related

AutoMapper assign property from parent type property

is there i way in autoMapper to assign child class property from parent class property. I have looked at other example out there but didn't quite get what I need so posting my issue here.
here's code
class ParentDB {
public int id;
public DateTime CreatedDate;
public string Name;
}
class ChildDB {
public int id;
publi string Name;
public int Number;
}
class ParentViewModel : IMapFrom <ParentDB> {
pulic int id;
pulic string Name;
public ChildViewModel child;
}
class ChildViewModel : IMapFrom <ChildDB> {
public int Id;
pulic string Name;
pulic DateTime ParentCreated;
}
public interface IMapFrom<T>
{
void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
}
Problem is that "ParentCreated" time in ChildViewMode needs to come from ParentDB. I have tried following with no success
class ParentViewModel : IMapFrom <ParentDB> {
pulic int id;
pulic string Name;
public ChildViewModel child;
public DateTime CreatedDate;
public void Mapping(Profile profile)
{
profile.CreateMap<ParentDB, ParentViewModel>()
.AfterMap( (s,d) => d.ChildViewModel.ParentCreated = d.CreatedDate);
}
}
var children = await Context.ParentDB
.ProjectTo<ParentViewModel>(mapper.ConfigurationProvider)
.ToListAsync()
with above although ParentViewModel.CreatedDate has date, ChildViewModel.ParentCreated is null. can some please explain why its not assigning date in AfterMap and hwo can this be fix.
Thanks
I am not how to do the map in the way you shared, since I can't see the IMapFrom <T> interface.
Maybe you can try below:
var parent = new ParentDB { id = 1, Name = "AA", CreatedDate = DateTime.Now.AddDays(1) };
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<ParentDB, ParentViewModel>()
.AfterMap((s, d) => d.ChildViewModel.ParentCreated = s.CreatedDate);
});
var mapper = configuration.CreateMapper();
ParentViewModel parentViewModel = mapper.Map<ParentViewModel>(parent);
Also you should initlize the ChildVewModel in the ParentViewModel, otherwise it will occur a NullReference exception
public class ParentViewModel
{
public ParentViewModel()
{
ChildViewModel = new ChildViewModel();
}
public int id;
public string Name;
public ChildViewModel ChildViewModel;
}
Result:

Can I define an object to a model with Play framework?

UserRole is an abstract class, it has three concrete classes with three different roles. However, each time I crate a new User with a new Role, the Role remains null!
Here is the code of the User:
#Entity
public class User extends Model {
#Id
public Long id;
#Constraints.Required
#Formats.NonEmpty
#Column(unique = true)
public String email;
#Constraints.Required
#Formats.NonEmpty
#Column(unique = true)
public String fullname;
public String confirmationToken;
#Constraints.Required
#Formats.NonEmpty
public String passwordHash;
#Formats.DateTime(pattern = "yyyy-MM-dd HH:mm:ss")
public Date dateCreation;
#Formats.NonEmpty
public Boolean validated = false;
**public UserRole role;**
}

Trying to create and xml attribute for a parent node while using XMLSerialization

I am using the XMLSerialization class in .Net to serialize an object to XML. In trying to set up a specific layout for the XML but am struggling to figure out how to add an attribute to the parent node in collection of elements (specifically the ProgrammingLanguages element below):
<Devloper>
<FirstName IsNew="true">John</FirstName>
<LastName IsNew="true">Doe</LastName>
<ProgrammingLanguages>
<LanguageType isNew="true">VB</LanguageType>
<LanguageType isNew="false">C#</LanguageType>
</ProgrammingLanguages>
</Devloper>
I can add an attribute (IsNew) to a element if there isn't a hierarchy to that data such as the FirstName and LastName elements, but how do I add a attribute to the ProgrammingLanguages element and NOT the LanguageType element when the parameter being used is a list.
Above is the XML output I am getting from using the code below but I would like the results to be as follows.:
<Devloper>
<FirstName IsNew="true">John</FirstName>
<LastName IsNew="true">Doe</LastName>
**<ProgrammingLanguages isNew="true">**
<LanguageType>VB</LanguageType>
<LanguageType>C#</LanguageType>
</ProgrammingLanguages>
</Devloper>
My Code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dev As New Devloper
dev.FirstName.text = "John"
dev.FirstName.IsNew = True
dev.LastName.text = "Doe"
dev.LastName.IsNew = True
Dim l1 As New LanguageType
l1.text = "VB"
l1.isnew = True
Dim l2 As New LanguageType
l2.text = "C#"
l2.isnew = False
dev.ProgrammingLanguages.AddRange({l1, l2})
dev.toXML()
End Sub
End Class
<Serializable> Public Class Devloper
Public Sub toXML()
Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(Devloper))
Dim myWriter As StreamWriter = New StreamWriter("d:\myFileName.xml")
mySerializer.Serialize(myWriter, Me)
myWriter.Close()
End Sub
Public FirstName As New helperClass
Public LastName As New helperClass
Public ProgrammingLanguages As New List(Of LanguageType)
End Class
Public Class helperClass
<XmlText> Public text As String
<XmlAttribute> Public IsNew As Boolean
End Class
Public Class LanguageType
<XmlText> Public text As String
<XmlAttribute> Public isNew As Boolean
End Class
Any Ideas?
I did it in c# i think it will help you
what i got in xml file was:
<firstClass Name="ABC">
<CustomerPhones Count="2">
<phone Number="123" Address="Home" />
<phone Number="456" Address="Work" />
</CustomerPhones>
</firstClass>
I created these classes:
public class firstClass
{
[XmlAttribute]
public string Name { get; set; }
public Phones CustomerPhones { get; set; }
}
public class Phones
{
[XmlAttribute]
public string Count { get; set; }
[XmlElement("phone")]
public List<Phone> phones { get; set; }
}
public class Phone
{
[XmlAttribute]
public string Number { get; set; }
[XmlAttribute]
public string Address { get; set; }
}

Filter nested objects using Jackson's BeanPropertyFilter

I have the following objects:
#JsonFilter("myFilter")
public class Person {
private Name name;
private int age;
public Name getName() {return name;}
public void setName(Name name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
}
#JsonFilter("myFilter")
public class Name {
private String firstName;
private String lastName;
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
}
I wrote a method to marshall a Person object like this:
#Test
public void test() throws Exception {
Person person = new Person();
person.setAge(10);
Name name = new Name();
name.setFirstName("fname");
name.setLastName("lastname");
person.setName(name);
ObjectMapper mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("name.firstName"));
System.out.println(mapper.filteredWriter(filters).writeValueAsString(person));
}
What I'd like to see is JSON like this:
{"name":{"firstName":"fname"}}
Is something like that possible?
Ok, figured it out. Varargs would have made this a bit prettier, but oh well. Just hope I don't have two inner beans which have properties with the same name. I wouldn't be able to make the distinction between the two
FilterProvider filters = new SimpleFilterProvider()
.addFilter("myFilter", SimpleBeanPropertyFilter
.filterOutAllExcept(new HashSet<String>(Arrays
.asList(new String[] { "name", "firstName" }))));
There's a better way that solves problem with property name conflicts. Just add another filter to class Name ("nameFilter"):
#JsonFilter("personFilter")
public class Person {
private Name name;
private int age;
public Name getName() {return name;}
public void setName(Name name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
}
#JsonFilter("nameFilter")
public class Name {
private String firstName;
private String lastName;
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
}
And then add 2 filters, one for Person and one for Name:
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("personFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"))
.addFilter("nameFilter", SimpleBeanPropertyFilter.filterOutAllExcept("firstName"));

design of orm tool

I want to design a orm tool for my daily work, but I'm always worry about the mapping of foreign key.
Here's part of my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace OrmTool
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute:Attribute
{
public string Name { get; set; }
public SqlDbType DataType { get; set; }
public bool IsPk { get; set; }
}
[AttributeUsage(AttributeTargets.Class,AllowMultiple=false,Inherited=false)]
public class TableAttribute:Attribute
{
public string TableName { get; set; }
public string Description { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public class ReferencesAttribute : ColumnAttribut
{
public Type Host { get; set; }
public string HostPkName{get;set;}
}
}
I want to use Attribute to get the metadata of Entity ,then mapping them,but i think it's really hard to get it done;
public class DbUtility
{
private static readonly string CONNSTR = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
private static readonly Type TableType = typeof(TableAttribute);
private static readonly Type ColumnType = typeof(ColumnAttribute);
private static readonly Type ReferenceType = typeof(ReferencesAttribute);
private static IList<TEntity> EntityListGenerator<TEntity>(string tableName,PropertyInfo[] props,params SqlParameter[] paras) {
return null;
}
private static SqlCommand PrepareCommand(string sql,SqlConnection conn,params SqlParameter[] paras) {
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.Connection = conn;
if (paras != null)
cmd.Parameters.AddRange(paras);
conn.Open();
return cmd;
}
}
I don't know how to do the next step, if every Entity has it's own foreign key,how do I get the return result ? If the Entity like this:
[Table(Name="ArtBook")]
public class ArtBook{
[column(Name="id",IsPk=true,DataType=SqlDbType.Int)]
public int Id{get;set;}
[References(Name="ISBNId",DataType=SqlDataType.Int,Host=typeof(ISBN),HostPkName="Id")]
public ISBN BookISBN{get;set;}
public .....more properties.
}
public class ISBN{
public int Id{get;set;}
public bool IsNative{get;set;}
}
If I read all ArtBooks from database and when I get a ReferencesAttribute how do I set the value of BookISBN?
in method EntityListGenerator ,I try to make a recursion that get mapping,but i don't know how to do next ,for each foreign key i'll read data from database? or get all foreign then mapping? those all too bad.