Trying a best solution? - java

I'm looking for a solution to my problem. I have 2 java class of domain. Graduacao and Aluno, in Graduacao I have an attribute "graus" that is a Collection.
In Aluno class, I have collection attribute "List graduacao".
I add the Graduacao in a JComboBox about ComboBoxModel and when user selected a Graduacao I have a JList that show the "graus" of Graduacao.
What I need is get Graduacao and graus that user choose and add to Aluno and persist after show results in a JTable with AbstractTableModel.
I'm trying this
#Entity
#Table(name="graduacao")
public class Graduacao {
#Id #GeneratedValue
private Integer id;
#NotNull #Column(unique = true)
private String graduacao;
#ElementCollection
#CollectionTable(name="graduacao_grau", joinColumns=#JoinColumn(name="id_graduacao"))
#Column(name="grau")
private List<String> graus;
//get and set
#Entity
#Table(name="aluno")
public class Aluno {
#Id #GeneratedValue
private Integer id;
//informacoes gerais
#NotNull
private String nome;
private String cpf;
private String rg;
private String nomePai;
private String nomeMae;
#Temporal(TemporalType.DATE)
private Date dtNascimento;
#Temporal(TemporalType.TIMESTAMP)
private Date dtCadastro;
private String status;
private String observacoes;
//logradouro
private String endereco;
private String bairro;
private String complemento;
private String cidade;
private String cep;
#Enumerated(EnumType.STRING)
private EstadoBrasileiro uf;
//contato
#ElementCollection
#CollectionTable(name="telefone_aluno", joinColumns=#JoinColumn(name="id_aluno"))
#Column(name="telefone")
private List<String> telefones;
private String email;
//graduacao
#OneToMany #JoinColumn(name="id_aluno")
private List<Graduacao> graduacao;
#Temporal(TemporalType.DATE)
private Date dataGraduou;
//federacao
#OneToMany #JoinColumn(name="id_federacao")
private List<Federacao> federacao;
//get and set
here the print
/** edit */
I solved the problem, here the project: http://www.4shared.com/zip/1Gbj-IZLce/project_example.html

A complete example is beyond the scope of StackOverflow. Two approaches are common, although neither is simple:
Create a custom TableModel that uses JPA queries and entities to implement the methods required by AbstractTableModel; a very simple example using JComboBox is shown here; a complete TableModel example with pagination is shown here.
Use org.jdesktop.beansbinding, shown here and mentioned here and here.
A number of ancillary links related to this topic are shown in this answer.

Related

Ebean and Play! not filtering columns with .select()

I'm trying to fetch just a part of the model using Ebean in Play! Framework, but I'm having some problems and I didn't found any solutions.
I have these models:
User:
#Entity
#Table(name = "users")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class User extends Model{
#Id
private int id;
#NotNull
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "last_name")
private String lastName;
#NotNull
#Column(nullable = false)
private String username;
#NotNull
#Column(nullable = false)
private String email;
private String gender;
private String locale;
private Date birthday;
private String bio;
#NotNull
#Column(nullable = false)
private boolean active;
private String avatar;
#Column(name = "created_at",nullable = false)
private Date createdAt;
#OneToMany
private List<UserToken> userTokens;
// Getters and Setters omitted for brevity
}
UserToken:
#Entity
#Table(name = "user_tokens")
public class UserToken extends Model {
#Id
private int id;
#Column(name = "user_id")
private int userId;
private String token;
#Column(name = "created_at")
#CreatedTimestamp
private Date createdAt;
#ManyToOne
private User user;
// Getters and Setters omitted for brevity
}
And then, I have a controller UserController:
public class UserController extends Controller{
public static Result list(){
User user = Ebean.find(User.class).select("firstName").where().idEq(1).findUnique();
return Results.ok(Json.toJson(user));
}
}
I expected that, when using the .select(), it would filter the fields and load a partial object, but it loads it entirely.
In the logs, there is more problems that I don't know why its happening.
It is making 3 queries. First is the one that I want. And then it makes one to fetch the whole Model, and another one to find the UserTokens. I don't know why it is doing these last two queries and I wanted just the first one to be executed.
Solution Edit
After already accepted the fact that I would have to build the Json as suggested by #biesior , I found (out of nowhere) the solution!
public static Result list() throws JsonProcessingException {
User user = Ebean.find(User.class).select("firstName").where().idEq(1).findUnique();
JsonContext jc = Ebean.createJsonContext();
return Results.ok(jc.toJsonString(user));
}
I render only the wanted fields selected in .select() after using JsonContext.
That's simple, when you using select("...") it always gets just id field (cannot be avoided - it's required for mapping) + desired fields, but if later you are trying to access the field that wasn't available in first select("...") - Ebean repeats the query and maps whole object.
In other words, you are accessing somewhere the field that wasn't available in first query, analyze your controller and/or templates, find all fields and add it to your select (even if i.e. they're commented with common HTML comment in the view!)
In the last version of Play Framework (2.6) the proper way to do this is:
public Result list() {
JsonContext json = ebeanServer.json();
List<MyClass> orders= ebeanServer.find(MyClass.class).select("id,property1,property2").findList();
return ok(json.toJson(orders));
}

How to put propper DBFLow annotation

I want to insert doctor object to database, how should I put annotations for properties?
I tried to do it with te code shown below.
But i don't know how to do it on list properties specializations and phoneNumbers.
#Table(databaseName = WMDatabase.NAME)
public class Doctor extends BaseModel{
#Column
#PrimaryKey
#Unique(unique = true)
private String doctorId;
#Column
private FullName fullName;
#Column
private String organizationId;
#Column What shuld i put here?????
private List<Specialization> specializations;
#Column What shuld i put here?????
private Contacts contacts;
}
Below are the classes I use for doctor attributes:
public class Contacts extends BaseModel {
private List<PhoneNumber> phoneNumbers;
private String email;
private String fax;
}
public class Specialization extends BaseModel {
#Column
#PrimaryKey
#Unique(unique = true)
private String doctorId;
#Unique(unique = true)
private String specializationName;
public String getSpecializationName() {
return specializationName;
}
public void setSpecializationName(String specializationName) {
this.specializationName = specializationName;
}
DBFlow is a relational database system (not a mongo-type key/value store) and doesn't support lists as columns, according to the doc here.
List : List columns are not supported and not generally proper for a relational database. However, you can get away with a non-generic List column via a TypeConverter. But again, avoid this if you can.
The documentation on relationships may help you refine the model to suit your needs.

Correct way to get model list in another model

I am working on a spring mvc app in which there are 2 entities, contact and location. Following are my contact and location models:
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#Column(name="locationid")
private int locationId;
}
Location model:
#Entity
#Table(name="Location")
public class LocationModel {
#Id
#Column(name="locationid")
#GeneratedValue
private int locationId;
#Column(name="locationname")
private String locationName;
#Column(name="locationdesc")
private String locationDescription;
#Column(name="type")
private String locationType;
#Column(name="address")
private String address;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="district")
private String district;
#Column(name="lattitude")
private String lattitude;
#Column(name="longitude")
private String longitude;
}
In contact dao, I am getting contact list using below code:
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ContactModel.class);
criteria.addOrder(Order.asc("contactName"));
return criteria.list();
Now I need to show contact list on contact home page which will show contact name and its corresponding location name.
To show the contact list, I need to create join in contact and location tables. Is this the proper way? How can we do this in hibernate?
Also is it the proper way to add location entity in contact entity, or do I have to use location model in contact?
You have to relate your both entities with relation .I am assuming that ContactModel have One-To-One relation with LocationModel
Change your ContactModel to
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#OneToOne
#Column(name="locationid")
private LocationModel location;
}
and do the rest of thing same as you are doing select only the ContactModel List objects.
public List<ContactModel> allContactModel(){
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ContactModel.class);
criteria.addOrder(Order.asc("contactName"));
return criteria.list();
}
and get the value of location in your controller by iterating over list ContactModel and fetch the LocationModel object from ContactModel as you fetch normal variable by ClassName.Fieldname.Here It will Give you a LocationModel object
List<ContactModel> mylist=ContactModel.allContactModel();
for(ContactModel cm: mylist){
LocationModel lm=ContactModel.getLocationModel();
System.out.println(cm.getContactName+" location is "+lm.getLocationName);
}
Now you have the LocationModel, you can fetch its further values also.
You can also further enhance this onetoone relation by specifying fetchtype,cascadetype etc accoding to your requirements.
Note:Assuming that you are have getter and setter in your model
i think the right way is that the contact can have a location, now add a location object to your contact, something like this:
#Entity
#Table(name="Contact")
public class ContactModel {
...
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinColumn(name = "locationid", nullable = false)
private LocationModel location;
// can be removed
#Column(name="locationid")
private int locationId;
...
}
if you have this you get the location object when you call a contact record

Mapping one-to-many relationship using QueryDSL SQL

Lets say I have this two bean entities:
public class Audit {
private String code;
private java.sql.Timestamp creationDate;
private String creatorId;
private java.sql.Timestamp deletionDate;
private String description;
private String id;
private String name;
private String notes;
private Short status;
private List<AuditParticipant> participants;
}
and :
public class AuditParticipant {
private String auditId;
private String department;
private String id;
private String name;
private String notes;
private String role;
private String surname;
}
... where Audit can have 1..n Participants, how can I use QueryDSL SQL to project the list of the participants into Audit bean (get all participants that belongs to audit)?
The beans were generated using QueryDSL code generation.
Thanks
Querydsl provides result aggregation functionality for such cases http://www.querydsl.com/static/querydsl/3.1.1/reference/html/ch03s02.html#d0e1634
In this case it would be something like
query.from(audit)
.innerJoin(participant).on(...)
.transform(groupBy(audit.id).as(audit, list(participant)));
See these examples for other groupBy options https://github.com/mysema/querydsl/blob/master/querydsl-collections/src/test/java/com/mysema/query/collections/GroupByTest.java

org.hibernate.ObjectNotFoundException issue with using list()

The following query throws the exception:
Query query = session.createQuery("from Associate as a order by a.username asc");
associates = query.list();
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ca.mypkg.model.Associate#0]
If I create an entry in the database with id of 0 it works just fine. I don't really get it because I'm just trying to load all the entries in the db not just a specific one.
Similar questions I've found have been concerned with trying to load an object with a given ID I'm doing no such thing.
Associate class:
#Table(name = "user")
#XmlRootElement(name = "associate")
public class Associate implements Serializable {
private String username;
private String password;
private String firstName;
private String lastName;
private String userType;
private int id;
private String email;
private String isActive;
private Department dept;
private String lastUpdated;
private String associate_type;
// ...
#Id
#GeneratedValue
public int getId() {
return id;
}
#OneToOne
#JoinColumn(name = "dept")
public Department getDept() {
return dept;
}
From my experience this type of error message usually means it does not find joined entity by mentioned id, and not the entity requested in the query (Associate, in your case).
My guess is that Associate class contains a join entity which has primitive type primary key.

Categories

Resources