Hibernate Id Sequence Resulting null in Entity having two columns with sequence - java

I have one Table in postgresql database with two id Sequence.
#JsonProperty("id")
#Column(name = "id", nullable = false,unique=true)
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY,generator = "order_seq_gen")
#SequenceGenerator(name = "order_seq_gen", sequenceName ="order_id_seq")
private Integer id;
#JsonProperty("state")
private String state;
#JsonProperty("order_id")
#Column(name="order_id", nullable=false, unique=true, insertable = false,
updatable = true, columnDefinition = "BIGINT DEFAULT nextval('order_idgen_seq')")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "order_seq_gen")
#SequenceGenerator(name = "order_seq_gen", sequenceName ="order_idgen_seq")
private Integer orderId;
This is my pojo.
My issue with the orderId, if I call my CRUD Repository save it is creating new record with those sequence starting values,
while returning the object orderId is resulting null but it is there in my table.
I have checked with the pojo and column mapping everything is fine but I'm not getting where it went wrong.
Another id sequence is returning without any issue but while coming to orderId it is resulting always null.
Please help me to solve this, Thankful to them.

I didn't think #GeneratedValue worked unless the #Id column was also present.
You could try this instead:
#Generated(GenerationTime.INSERT)
private Integer orderId;
and then make sure your Postgres column was defined as SERIAL type, which will automatically create a sequence named tablename_order_id_seq to use for it.

Related

How to get the next value in a sequence with #GeneratedValue in spring-jpa

There is already some data available in table, where id being the primary key for me. So when i trying to invoke my spring jpa code to add values to the table i'm using #GeneratedValue for the primary key.
But this way is generating value which is already present in DB. so my application is throwing an exception.
Is there any way i can get the current value from the table and increment my primary key id wrt the previous value of ID present in the table
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "id", updatable = false, nullable = false)
private int id;
Let's say your max id in DB currently is 500. Run this:
CREATE SEQUENCE seq_name_in_db START WITH 501;
And change to:
#Id
#SequenceGenerator(name = "some_seq", sequenceName = "seq_name_in_db")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "some_seq")
private int id;
UPDATE: (Solution to OP's comment)
While inserting directly, do this:
INSERT INTO some_table (id, ...) VALUES (seq_name_in_db.NEXTVAL, ...);
When You create the sequence, you can let it start with a certain value e.g.
CREATE SEQUENCE XX_SEQ
START WITH 100
INCREMENT BY 1 ;

One to One Mapping in Hibernate Unidirectional with MySQL DB?

Am new to Hibernate and MySQL, i have two Table like OFFER_TABLE and OFFER_LIKES_DISLIKES
OFFER_TABLE Columns
OFR_ID(PK)
OFR_MSG
OFFER_LIKES_DISLIKES Columns
OFFER_LIKES_DISLIKES_ID
OFR_ID(FK)
LIKE
DISLIKE
I want to map OFFER_TABLE and OFFER_LIKES_DISLIKES, Access the OFFER_LIKES_DISLIKES data through OFFER_TABLE. Am using One to One Mapping but its not Working.
Hibernate Annotation Mapping Java Class
Offers.class
#Id
#GeneratedValue
#Column(name = "OFR_ID", length = 11, nullable = false)
private int offer_id;
#OneToOne
#JoinColumn(name="OFR_ID", unique = true)
#OneToOne(cascade = CascadeType.ALL)
private MessageLikeDislikesDAO likeDislikes;
LikeDislike.class
#GeneratedValue
#Column(name="LIKES_DISLIKES_ID", length = 11, nullable = false)
private int likes_dislikes_id;
#Expose
#Column(name="OFR_ID", length = 11, nullable = false)
private int offer_id;
When I get the Data of Offers, want Like and Dislike data associated with it. In LikeDislike table OFR_ID is UNIQUE. Am used One to One. But i didn't get the data of LikeDislike. Which one is best way to took that data. Help me to solve this issue.
There are many problems:
You're creating an association with a DAO instead of creating an association with an entity
You're storing the ID of the offer in the LikeDislike entity instead of storing an association with the Offer entity
You're saying that there is a join column named OFR_ID and referring to the LikeDislike entity in the OFFER table.
You disrespect Java naming conventions
You're setting two OneToOne annotations on the same field
The mapping should be:
Offer:
#Id
#GeneratedValue
#Column(name = "OFR_ID", length = 11, nullable = false)
private Integer offerId;
#OneToOne(mappedBy = "offer", cascade = CascadeType.ALL)
private LikeDislike likeDislike;
LikeDislike:
#GeneratedValue
#Column(name="LIKES_DISLIKES_ID", length = 11, nullable = false)
private Integer likeDislikeId;
#Expose
#OneToOne
#JoinColumn(name="OFR_ID", length = 11, nullable = false)
private Offer offer;
Relevant documentation

Is there any way to get unique elements in list when realizing ManyToMany association?

I have Language entity. And I want to realize ManyToMany association with the same table. translation_ways table have just two fields fromLangId int(3) and toLangId int(3).
#Entity(name = "Language")
#Table(name = "language")
public class Language implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "language_id")
private int id;
#NotBlank
#Column(name = "short_name", unique = true, length = 2, nullable = false)
private String shortName;
#NotBlank
#Column(name = "full_name", unique = true, nullable = false)
private String fullName;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "translation_ways",
joinColumns = #JoinColumn(name = "fromLangId"),
inverseJoinColumns = #JoinColumn(name = "toLangId"))
private Set<Language> toLangs;
//getters and setters here
//ovverrided equals() & hashCode()
}
What I want to do is to get the list of all Languages (with Set of the Languages entities joined by translation_ways table). The problem is that Criteria.list() returns list with duplicates. Amount of duplicates in the list is equal to how many times current id appears in the translation_ways.fromLangId column. In my case it is redundant information and I want to get list of unique Objects.
So the first question is if there is the some recommended or best of the best way to get this list without redundant elements? Convert returned ArrayList to LinkedHashSet? Or maybe I just did something wrong with my Criteria???
Also, have one more related question. If I'll call this query in the second time hibernate will take data from a cache, am I right?
I will appreciate any recommendations, ideas, links and help. Thanks everyone in advance.
my request:
Criteria c = this.template.getSessionFactory().getCurrentSession().createCriteria(Language.class);
c.setCacheable(true)
.setCacheMode(CacheMode.NORMAL)
.setCacheRegion("staticLangList");
List<Language> ls = c.list();
return ls;
P.S. Hibernate version is 5.0.1.Final.
use setResultTransformer in Criteria to avoid duplicates.
c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

How to insert records using the Entity Manager without defining the Primary Key field?

I have trying to insert a record into the database (MySQL), using Entity Class and Entity Manager. But one of the field is an auto incrementing primary key, so unless I provide an value manually, the insertion is not successful.
public boolean newContributor(String name, String email, String country, Integer contactable, String address) {
Contributors contributor = new Contributors(); //entity class
contributor.setId(??????); //this is Primary Key field and is of int datatype
contributor.setName(name);
contributor.setEmail(email);
contributor.setCountry(country);
contributor.setContactable(contactable);
contributor.setAddress(address);
em.persist(contributor);
return true;
}
How to solve such problem? Is there a way to tell the entity manager to attempt the insert without the ID field and use NULL value instead.
Update: Here is a portion of the entity class defining the id
...
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
....
Is there a way to tell the entity manager to attempt the insert without the ID field and use NULL value instead?
Sure. You need to remove the #NotNull annotation for id field in the #Entity definition, and also remove the row:
contributor.setId(??????);
from method newContributor(). The reason for this is that the #NotNull annotation enforces a validation check in the JPA stack. It doesn't mean that the field is NOT NULL at a database level. See here a discussion about this issue.
The rest of the code looks fine.

How to dynamically set id number series using javax persistence / seam

I have an entity simply called Order. The strategy I'm using now for the ID is:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ORDER_ID")
private Long id;
Now, hardcoding another startvalue seems easy:
#Entity
#SequenceGenerator(name = "SequenceIdGenerator",
sequenceName = "SEQ_ID_GEN", initialValue = 50,
allocationSize = 20)
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SequenceIdGenerator")
#Column(name = "ORDER_ID")
private Long id;
But that's hardcoded to 50. Can I set that value dynamically? Best would be if I could have it stored in the database or in a properties file?
Or is it not best practice to set id dynamically?
Usually, but not always, the easiest way is to create a sequence in your database and to use that sequence. I hope there is not much mistakes in following example:
#Id
#GeneratedValue(generator="IdSeq")
#SequenceGenerator(name="IdSeq",sequenceName="SEQ_ID_GEN", allocationSize=20)

Categories

Resources