How to find all data in DB using Hibernate? - java

I have following classes
#Entity
#Table(name="prm_user_permission")
public class UserPermission {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="prm_permission_id")
private Integer permissionId;
#Column(name="prm_permission_name")
private String permissionName;
#Column(name="prm_short_description")
private String shortDescription;
#Column(name="prm_description")
private String description;
#Column(name="prm_url")
private String permissionUrl;
#Column(name="prm_control")
private String control;
#Column(name="prm_create_user")
private Integer creatUser;
#Column(name="prm_parent_id")
private Integer parentId;
#Column(name="prm_system_id")
private Integer systemId;
// Getter and Setter
And my code is
public List<UserPermission> findAllBySystemId(int systemId) {
List<UserPermission> userPermission = criteria().setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(eq("UserPermission.systemId", systemId).list();
return userPermission;
}
Now i want to get all data from this (UserPermission) table by "systemId".If i pass systemId=1 then it should give all data where the column is '1'.
what is wrong in my code? while running it shows error like
org.hibernate.QueryException: could not resolve property: UserPermission of:
com.kgfsl.collections.core.security.models.UserPermission
Plz anybody help

What do the criteria() method returns?
And, try with systemId directly (eg: remove the UserPermission.)

Try with Restrictions.eq()
public List<UserPermission> findAllBySystemId(int systemId) {
List<UserPermission> userPermission = criteria().setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.eq("systemId", systemId)).list();
return userPermission;
}
Assuming that your criteria() method would be,
session.createCriteria(UserPermission.class)

Related

How to set and get value from the composite key

I am trying to set the value cid in student class using SubjectMark->private String cid;
How to set and get value in my controller.
Entity's and controller method below:
#Entity
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private SubjectMark id;
private String fullName;
private Integer totalMarks;
private Double percentage;
private String grade;
//Setters and getters
}
//Composit class
#Embeddable
public class SubjectMark implements Serializable {
//Composit key
private String cid;
//Setters and getters
}
In my controller I try to set value like this:
#RequestMapping(value="getstdata",method=RequestMethod.GET)
#ResponseBody
public String getstdata(#RequestParam(value="cid")String cid){
//Some code
try{
Student st=new Student();
st.getId().setCid(cid);//Set value like this but it is getting null pointer exception
//some code
//retuen some value
}
Please help me!
1st part of question:
I am trying to set the value cid in student class using SubjectMark->private String cid; How to set and get value in my controller.
#Entity
#Table
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private SubjectMark subjectMarkId;
private String otherField;
// setters, getters
}
//Composite class
#Embeddable
public class SubjectMark implements Serializable {
private String cId;
// setter, getter
}
//Controller
#GetMapping(value = "getstdata")
public String getStData(#RequestParam(value="cid") String cid) {
Student student = new Student();
student.setSubjectMark(new SubjectMark());
student.getSubjectMark().setCId(cid);//cid value dynamic
// some other code
return "";
}
2nd part of question:
Now, one of the reason null exception happens when you try to call a method(either setter or getter) from a null object.
you need to write a get set method in your class I guess...
try writing something like
private String cid;
public String Cid { get => cid; set => cid = value; }

Failed to convert request element in entity with #IdClass

I have the following setup:
#Entity
#IdClass(MemberAttributePk.class)
public class MemberAttribute {
#Id
#ManyToOne #JoinColumn(name="member_id")
protected Member member;
#Id
protected String name;
private String value;
public MemberAttribute() {}
// get & set
}
And the id class:
public class MemberAttributePk implements Serializable {
protected Member member;
protected String name;
public MemberAttributePk() {}
// get & set
}
I have defined a simple Spring Data repository for MemberAttribute:
#Repository
public interface MemberAttributeRepo extends JpaRepository<MemberAttribute, MemberAttributePk> {
}
Now, all I want to do is persist a member attribute to the database:
public void saveAttribute(Member member, String name, String value) {
MemberAttribute attr = new MemberAttribute(member, name, value);
attributeRepo.save(attr);
}
However, I end up with this server exception:
2016-08-28 00:24:20.673 WARN 5656 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver :
Failed to convert request element: org.springframework.beans.ConversionNotSupportedException:
Failed to convert property value of type [java.lang.Long] to required type [com.example.Member] for property 'member'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.Long] to required type [com.example.Member] for property 'member':
no matching editors or conversion strategy found
Any idea what am I doing wrong?
Thanks!
Simply your code is not JPA compliant. The cause of problem is that you use Member as a part of your PK.
The PK can only be made up of fields of the following Java types
Primitives : boolean , byte , char , int , long , short
java.lang : Boolean , Byte , Character , Integer , Long , Short , String , Enum , StringBuffer
java.math : BigInteger java.sql : Date , Time , Timestamp
java.util : Date , Currency, Locale, TimeZone, UUID
java.net : URI, URL
javax.jdo.spi : PersistenceCapable
This should work:
#Embeddable
public class MemberAttributePk implements Serializable {
#Column(name = "member_id")
protected Long memberId;
#Column(name = "name")
protected String name;
public MemberAttributePk() {}
// get & set
}
#Entity
public class MemberAttribute {
#EmbeddedId
protected MemberAttributePk memberAttributePk;
#ManyToOne
#JoinColumn(name="member_id")
protected Member member;
private String value;
public MemberAttribute() {}
// get & set
}
Or the same with #ClassId
public class MemberAttributePk implements Serializable {
protected Long memberId;
protected String name;
public MemberAttributePk() {}
// get & set
}
#Entity
#IdClass(MemberAttributePk.class)
public class MemberAttribute {
#Id
#Column(name = "member_id")
protected Long memberId;
#Id
#Column(name = "name")
protected String name;
#ManyToOne
#JoinColumn(name="member_id")
protected Member member;
private String value;
public MemberAttribute() {}
// get & set
}
you can try save it using your MemberRepository, because I believe your Member class and MemberAttribute class have a one to many relationship reference, here below is the example
Member class
#Entity
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long id;
#OneToMany(mappedBy = "Member", cascade = CascadeType.ALL)
private Set<MemberAttribute> mMemberAttributes = new HashSet<>();
public void setMemberAttributes(Set<MemberAttribute> mMemberAttributes){
this.mMemberAttributes = mMemberAttributes;
}
public Set<MemberAttribute> getMemberAttributes(){
return mMemberAttributes;
}
// other code
}
MemberRepository class
public interface MemberRepository extends JpaRepository<Member, Long> {
}
code inside your save function
public void saveAttribute(Member member, String name, String value) {
MemberAttribute attr = new MemberAttribute(member, name, value);
member.getMemberAttributes().add(attr);
memberRepository.save(member);
}

Setting up query for specific field of Hibernate entity

I use spring and hibernate. The following situation occured and I don't know if it's really possible to implement. Will appreciate any help.
For example, there is a hibernate entity
#Entity
public class TestEntity {
private String field1;
private String field2;
private String specField;
#Column(name = "field1")
public String getField1() {
return field1;
}
#Column(name = "field2")
public String getField2() {
return field2;
}
public String getSpecField() {
return (field1 != null ? field1 : field2);
}
}
And I need the value for specField to be generated by SQL query and not by java code.
Something like this
#Entity
public class TestEntity {
private String field1;
private String field2;
private String specField;
#Column(name = "field1")
public String getField1() {
return field1;
}
#Column(name = "field2")
public String getField2() {
return field2;
}
#Query(value= "COALESCE(field1, field2)")
public String getSpecField() {
return specField;
}
}
I was told that there should be ability to do so. But didn't find anything that approves this.
it's not actually important what exactly query does. I need that specField will be taken by some query and not by java code. Is it possible?
Thanks for help.
UPDATE Thanks to #premkumar, for advicing to use #Formula
So now I have
#Entity
public class TestEntity {
private String field1;
private String field2;
private String specField;
#Column(name = "field1")
public String getField1() {
return field1;
}
#Column(name = "field2")
public String getField2() {
return field2;
}
#Formula("COALESCE(field2, field2)")
public String getSpecField() {
return (field1 != null ? field1 : field2);
}
}
But app fails to start on bean initialization with
NullPointerException at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory
I tried also the following:
Put formula above "private String specField" - app started, but hibernate failed on could not find spec_field in database
Put #Formula and #Transient on getter - app started, no errors, but specField is always null. It looks like hibernate totally ignored it
If you are using hibernate, try the following:
#Formula("COALESCE(field1, field2)")
public String getSpecField() {
return specField;
}
Note:- As far as I know there is no alternative in JPA. Beware this will mixup hibernate and jpa annotations.
Why not:
public String getSpecField() {
return MoreObjects.firstNonNull(field1,field2);
}
You can leverage the JPA Callback methods:
Create a EntityListener:
public class MyEntityListener {
#PrePersist
#PreUpdate
public void prePersist(Object object) {
if(object instanceOf TestEntity ) {
object.specField = object.field1 != null ? object.field1 : object.field2
}
}
}
Annotate your class with #EntityListener:
#Entity
#EntityListeners(MyEntityListener .class)
public class TestEntity {
private String field1;
private String field2;
private String specField;
//default cons - getters and setters
}

Play Framework: No #javax.persistence.Id field found in class

I have this Play Model class that I'm trying to modify an object of, and when I want to save it, I get the following exception:
java.lang.RuntimeException: No #javax.persistence.Id field found in class [class models.Contact]
at play.db.ebean.Model._idAccessors(Model.java:39)
at play.db.ebean.Model._getId(Model.java:52)
The class:
#Entity
public class Contact extends Model implements Person {//, Comparable<Contact>{
private Long id;
private Client client;
#Required
private String email;
private String profil_picture;
private Boolean active = new Boolean(true);
private Boolean favorite = new Boolean(false);
#Transient
private Boolean profile_pic_url_init = new Boolean(false);
#Id
#GeneratedValue
public Long getId() {
return id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="client_id")
public Client getClient(){
return client;
}
public void setClient(Client client){
this.client= client;
}
#Column
public Boolean getFavorite() {
return favorite;
}
public void setFavorite(Boolean is_favorite) {
this.favorite = is_favorite;
}
....
}
The code calling the save() method:
List<Contact> contacts_list = current_client.getContacts();
for (Contact c : contacts_list) {
c.setFavorite(false);
c.save();
}
The class actually has an #Id annotation, so any guesses of why this doesn't work? I tried looking it up on google, but couldn't find much about this error. Thanks in advance!
Move #Id annotation to id field instead of its getter.

Hibernate mapping - Could not determine type for pg-uuid

I'm actually trying to use the Hibernate ORM with java annotations for the mapping. I use PostgreSQL for my database and its UUID type. As I have seen on others posts, when I want to map the UUID pgsql type to the UUID Java type, I should add #Type(type="pg-uuid") to every UUID fields. The problem is that it doesn't seem to be recognized by hibernate as I get this:
org.hibernate.MappingException: Could not determine type for: pg-uuid, at table: ev_session, for columns: [org.hibernate.mapping.Column(user_id)]
I can't find anything on Google mentionning that, so I really have no clue of where I should look.
Here is my mapped class. The table uses two UUID as primary key, that's why I had to create a nested class representing it. I'm not sure that I did it right though.
#Entity
#Table(name="ev_session")
public class SessionDb {
////////////////////////
// VARIABLES
////////////////
#Id
private PrimaryKey primaryKey;
#Column(name="date")
private Date timestamp;
////////////////////////
// NESTED CLASSES
////////////////
#Embeddable
private class PrimaryKey implements Serializable {
private static final long serialVersionUID = 7124577164356450734L;
#Type(type="pg-uuid")
#Column(name="user_id")
public UUID userID;
#Type(type="pg-uuid")
#Column(name="key")
public UUID token;
}
////////////////////////
// CONSTRUCTORS
////////////////
public SessionDb() {
this.primaryKey = new PrimaryKey();
}
////////////////////////
// METHODS
////////////////
#Override
public String toString() {
return this.primaryKey.token + " associated to " + this.primaryKey.userID + " at " + this.timestamp;
}
////////////////////////
// GETTERS/SETTERS
////////////////
public final UUID getUserID() {
return this.primaryKey.userID;
}
public final void setUserID(UUID userID) {
this.primaryKey.userID = userID;
}
public final UUID getToken() {
return this.primaryKey.token;
}
public final void setToken(UUID token) {
this.primaryKey.token = token;
}
public final Date getTimestamp() {
return timestamp;
}
public final void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
Thanks for your help
I guess you should use a Generator:
#Id #GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
Take a look here.
Some more documentation here.
In case of xml mapping you can add
<typedef class="org.hibernate.type.PostgresUUIDType" name="pg-uuid" />
Like described in https://developer.jboss.org/thread/229747 but I don't know how to configure this with annotations.

Categories

Resources