JPA - manytoone cascading - java

I've got two entities
ServiceDownload.java
#Entity
public class ServiceDownload implements Serializable {
private static final long serialVersionUID = -5336424090042137820L;
#Id
#GeneratedValue
private Long id;
#Length(max = 255)
private String description;
private byte[] download;
private String fileName;
#ManyToOne
private Service service;
Service.java
#Entity
public class Service implements Serializable {
private static final long serialVersionUID = 4520872456865907866L;
#EmbeddedId
private ServiceId id;
#Length(max = 255)
private String servicename;
#Column(columnDefinition = "text")
private String highlightsText;
#Column(columnDefinition = "text")
private String detailsText;
#Column(columnDefinition = "text")
private String productText;
#Column(columnDefinition = "text")
private String dataText;
#ManyToMany(mappedBy = "services")
private Set<Machine> machines;
#OneToMany(targetEntity = ServiceDownload.class)
private List<ServiceDownload> serviceDownloads;
#OneToOne
private ServicePicture servicePicture;
When I create a new ServiceDownload Object and try to persists this I recieve a duplicate key exception. It seems that jpa tries to insert a new service object into the service table. How can I disable this behaviour?

You are using #GeneratedValue annotation for your #Id. According to JPA documentation, you should supply unique identifiers
By default, the application is responsible for supplying and setting entity identifiers (see #Id)
Try using a #SequenceGenerator and a sequence in your database to generate unique identifiers

Related

Why i get must use a #JoinColumn instead of #Column

i am tryning to join two entities where typDossAmo can have a list of DossMedic
but i get the following error:
Entity class [class ma.cnss.wstest.TypDossAmo] must use a #JoinColumn instead of #Column to map its relationship attribute [drugs].
public class TypDossAmo implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "ID")
private BigInteger id;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 9)
#Column(name = "NUM_DOSS")
private String numDoss;
#Column(name = "p_tab_medic")
#OneToMany(mappedBy="doss")
private List<DossMedic> drugs;........
public class DossMedic implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected DossMedicPK dossMedicPK;
#Column(name = "ID")
private BigInteger id;
#Column(name = "NOMBRE")
private BigInteger nombre;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="NUM_DOSS")
private TypDossAmo doss;
The idea of the annotation #Column is for common columns without any relationship with other tables, when you use #JoinColumn is to say to the ORM that two tables have a relationship and the way to join them is with this column.
In this case the solution is change the annotation #Column by #JoinColumn in TypDossAmo
public class TypDossAmo {
#JoinColumn(name = "p_tab_medic")
#OneToMany(mappedBy="doss")
private List<DossMedic> drugs;
}

Spring data jpa find by multiple fields in embedded key

I need to find an object using two fields of an embedded key
Here is the embedded key:
public class OrderItemId implements Serializable {
private static final long serialVersionUID = 1163347452811191867L;
#Column(name = "order_code", length = 25)
private String orderCode;
#Column(name = "barcode", length = 25)
private String barcode;
// ....
}
Here is the class of the object I want to query:
#Entity
#Table(name = "order_item")
public class OrderItem {
#EmbeddedId
#NotNull
private OrderItemId id;
#Column(name = "quantity")
private Integer quantity;
#Column(name = "price")
private Double price;
// ...
}
As in this StackOverflow Answer
To query by embedded key orderCode, I can write something like this
public List<OrderItem> findById_OrderCode(String orderCode);
and it works!
But I don't know how to query by both orderCode and barcode. I have tried some forms of and but no use.
Never mind, I have figured out the query, it is
public OrderItem findById_OrderCodeAndId_Barcode(String orderCode, String barcode);

How can i create only one record with Hibernate JPA Annotation

I have got 3 entity. These are: Tweet,Thread and Media. I am using Hibernate JPA Annotations. When i save one Thread object, it must trigger to tweet and automatically tweet must saved like thread and Tweet's "media" must saved of course.
You can see my entity class as below. Right now i'm working on Tweet beetween Thread. When i use these code, The number of thread is being recorded as much as tweet object. But i want that only one record inside thread.
Process must be like that after saved thread:
add a new record to Thread table. (only one row)
add all tweet to tweet table(all of "threadid" column same because these tweets belong only one thread!)
add all media to media table(all of "tweetid" column same )
Tweet Table:
#Entity
#Table(name = "tbl_tweet")
public class Tweet implements Serializable {
#Id
#GeneratedValue
private long id;
#Column(name = "tweetid")
private String tweetID;
private String parentTweetID;
private String avatar;
private String owner_name;
private String owner_nick;
private String content;
private String sent_time;
private String sent_date;
private String retweet_count;
private String like_count;
private String owner_link;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="threadid")
private Thread thread;
#OneToMany(mappedBy = "tweet",fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private List<Media> mediaURLs;
Thread Table:
#Entity
#Table(name = "tbl_thread")
public class Thread implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "threadid")
private String threadID;
#Transient
private List<Tweet> listOfTweets;
Media Table:
#Entity
#Table(name = "tbl_media")
public class Media implements Serializable {
#Id
#GeneratedValue
private long id;
private String mediaID;
private String mediaType;
private String mediaUrl;
private String mediaUrlHttps;
private String mediaVideoUrl;
#ManyToOne
#JoinColumn(name = "tweetid")
private Tweet tweet;
My expected and actual results:
http://prntscr.com/mkaul5
I changed that way. Right now it's working good. Long live annotations!
Tweet Table:
#Entity
#Table(name = "tbl_tweet")
public class Tweet implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(unique = true,nullable = false,name = "tweetID")
private String tweetID;
private String parentTweetID;
private String avatar;
private long owner_id;
private String owner_name;
private String owner_nick;
private String content;
private String sent_time;
private String sent_date;
private String retweet_count;
private String like_count;
#Transient
private String quotedTweetHtml;
#Transient
#JoinColumn(name = "threadid",referencedColumnName = "id")
private Thread thread;
#OneToMany(cascade = CascadeType.PERSIST,fetch = FetchType.EAGER)
#JoinColumn(name = "tweetID")
private List<Media> mediaURLs;
Thread Table:
#Entity
#Table(name = "tbl_thread")
public class Thread implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "threadid")
private String threadID;
#OneToMany(cascade = CascadeType.PERSIST,fetch = FetchType.EAGER)
#JoinColumn(name = "threadid")
private List<Tweet> listOfTweets;
Media Table:
#Entity
#Table(name = "tbl_media")
public class Media implements Serializable {
#Id
#GeneratedValue
private long id;
private String mediaID;
private String mediaType;
private String mediaUrl;
private String mediaUrlHttps;
private String mediaVideoUrl;
#Transient
#JoinColumn(name = "tweetID")
private Tweet tweet;

how to create table with 2 primary key fields hibernate

i'm trying to create tabel entity with composite primary key.
so i tried to create #Embeddable class with all the primary keys and use #EmbeddedId on the field that represents the primary keys. but i get this error:
Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
i wos tried to follow this link bat noting work
what i'm doing wrong?
here is my code
DocEntity
#Entity(name = "doc")
#Table(name = "doc")
public class DocEntity extends baseDataBase implements Serializable
{
private static final long serialVersionUID = 1L;
#EmbeddedId
private DocID docID;
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "DocID")
#JsonProperty
#NotEmpty
private short id;
#Column(name = "DocDescription")
#JsonProperty
#NotEmpty
private String docDescription;
#Column(name = "DocPath")
#JsonProperty
#NotEmpty
private String docPath;
// getters, setters ,equals, hashCode
}
DocID
#Embeddable
public class DocID implements Serializable
{
private static final long serialVersionUID = 1L;
#Column(name = "DocName")
#JsonProperty
#NotEmpty
protected String docName;
#Column(name = "DocVersion")
#JsonProperty
#NotEmpty
protected String docVersion;
// getters, setters ,equals, hashCode
}
what i'm doing wrong?

Entity without Primary Key ID

Hi I want to create an Entity which doesn't have an ID.
#Entity
#Table(name="USER_PROD_LIC_TYPE_ALL")
public class UserProdLicTypeAll {
#EmbeddedId
private UserProdLicTypeAllPK id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LICENSE_TYPE_ID")
private LicenseType licType;
....
}
since it doesn't have primary key i created Embeddable class as below:
#Embeddable
public class UserProdLicTypeAllPK {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LICENSE_TYPE_ID")
private LicenseType licType;
...
}
The combination of these two fields returns a unique value.
But it doesn't work. I get
org.springframework.beans.factory.UnsatisfiedDependencyException: exception.
Do i need to have references in User and LicenseType entities for both UserProdLicTypeAll and UserProdLicTypeAllPK? I have tried that also but still it doesn't work.
This is my private hell. I'm not sure what the best way to solve it properly.
My best solution is:
#Entity
#Table(name = TableName.AREA_USER)
#IdClass(UserAreaPK.class)
public class UserArea implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = UserAreaPK.C_AREA_ID)
private Long areaId;
#Id
#Column(name = UserAreaPK.C_USER_ID)
private String userId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = UserAreaPK.C_AREA_ID, insertable = false, updatable = false)
private Area area;
And
/**
* Primary key for the relationship User-Area
*/
public class UserAreaPK implements Serializable {
protected static final String C_AREA_ID = "area_id";
protected static final String C_USER_ID = "user_id";
private static final long serialVersionUID = 1L;
#Id
#Column(name = C_AREA_ID)
private Long areaId;
#Id
#Column(name = C_USER_ID)
private String userId;

Categories