Read from property file in entity - java

I have an attribute expiryDate in my entity. i want when i ceate an instance from this entity, i set the value of the attribute expiryDate. The value is in the application.yml file. I used Properties.getProperty in the construct but it didn't work
application.yml:
application:
token:
expiredIn: 1440
Token entity:
public abstract class Token implements Serializable {
#Id
private UUID id;
private int expiryIn;
public Token() {
this.expiryIn= Properties.getProperty("application.token.expiredIn");
}
}
#UPDATE
I used #Value but the value of expiration is always 0
public abstract class Token implements Serializable {
#Id
private String id;
private Date expiryDate;
#Value("${application.token.expiredIn}")
private static int expiration;
public Token() {
this.expiryDate = calculateExpiryDate(expiration);
}
private Date calculateExpiryDate(final int expiryTimeInMinutes) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(new Date().getTime());
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime());
}
}

Try:
public abstract class Token implements Serializable {
#Id
private UUID id;
#Value("${application.token.expiredIn}")
private int expiryIn;
}
#Value will take the value from application.yml file and inject it into expiryIn.

Related

Hibernate is not using the proxy of a session scope bean spring

I'm using Spring #Scope(value = "session", proxyMode=ScopedProxyMode.TARGET_CLASS) beans for objects that should be shared across a single Http-Session. This will provide for example one "Project" object for each User who is using my application.
To get this working I had to implement an interceptor for Hibernate that is returning the name of the class:
public class EntityProxySupportHibernateInterceptor extends EmptyInterceptor {
private static final long serialVersionUID = 7470168733867103334L;
#Override
public String getEntityName(Object object) {
return AopUtils.getTargetClass(object).getName();
}
}
With this interceptor I can use a Spring CrudRepository to save a Project-entity in the database:
#Repository
public interface ProjectRepository extends CrudRepository<Project, Integer> {
Project findByProjectId(int projectId);
}
Project-entity:
#Component
#Entity
#Table(name = "xxx.projects")
#Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class Project implements Serializable {
private static final long serialVersionUID = -8071542032564334337L;
private int projectId;
private int projectType;
#Id
#Column(name = "project_id")
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
#Column(name = "project_type")
public int getProjectType() {
return projectType;
}
public void setProjectType(int projectType) {
this.projectType = projectType;
}
}
Storing the Project in the database works as expected. I can have a look at the database and the correct values are inserted. Now I have a different entity that I'm creating the same way as the project and that I want to save in the database via a CrudRepository.
Here the problem begins. Hibernate is not inserting the values that I have set. Hibernate always only inserts null into the database. Reading the values in my Spring application is working as expected. I think that Hibernate is not using the proxy of the entity but the underlying blueprint of the object. How can I force Hibernate to use the proxy with the correct values?
Repository:
#Repository("DataInput001Repository")
public interface DataInputRepository extends CrudRepository<DataInput, DataInputId> {}
Entity:
#Component("DataInput001")
#Entity
#Table(name = "xx.data_input_001")
#Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
#IdClass(DatanputId.class)
public class DataInput implements Serializable {
private static final long serialVersionUID = -6941087210396795612L;
#Id
#Column(name = "project_id")
private int projectId;
#Column(name = "income")
private String income;
#Column(name = "income_increase")
private String incomeIncrease;
/* Getter + Setter */
}
Service:
#Service("DataInputService001")
public class DataInputServiceImpl implements DataInputService {
#Resource(name = "DataInputMapper001")
DataInputMapperImpl dataInputMapper;
#Resource(name = "DataInput001Repository")
DataInputRepository dataInputRepository;
#Resource(name = "DataInput001")
DataInput datanInput;
#Transactional
public void createDataInput(String json) throws Exception {
dataInputMapper.mapDataInput(json);
dataInputRepository.save(dataInput);
}
public DataInput getDataInput() {
return dataInput;
}
public void setDataInput(DataInput dataInput) {
this.dataInput = dataInput;
}
}

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);
}

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