I'm currently working on an application wherein I'm trying to access a local MySQL database, and specifically trying to run the code:
DataManagerImpl dm = new DataManagerImpl();
System.out.println(dm.findJobByCode("ABN54"));
As a basic check to see if I can actually query the database.
This is the start of the OrderTable entity class:
#Entity
#Table(name = "order_table")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "OrderTable.findAll", query = "SELECT o FROM OrderTable o")
, #NamedQuery(name = "OrderTable.findByOrderID", query = "SELECT o FROM OrderTable o WHERE o.orderID = :orderID")
, #NamedQuery(name = "OrderTable.findByTotalPrice", query = "SELECT o FROM OrderTable o WHERE o.totalPrice = :totalPrice")
, #NamedQuery(name = "OrderTable.findBySpecialInstructions", query = "SELECT o FROM OrderTable o WHERE o.specialInstructions = :specialInstructions")
, #NamedQuery(name = "OrderTable.findByStatus", query = "SELECT o FROM OrderTable o WHERE o.status = :status")
, #NamedQuery(name = "OrderTable.findByPaymentdetailID", query = "SELECT o FROM OrderTable o WHERE o.paymentdetailID = :paymentdetailID")
, #NamedQuery(name = "OrderTable.findByDateSubmitted", query = "SELECT o FROM OrderTable o WHERE o.dateSubmitted = :dateSubmitted")})
public class OrderTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "orderID")
private Integer orderID;
#Column(name = "total_price")
private Float totalPrice;
#Column(name = "special_instructions")
private String specialInstructions;
#Column(name = "status")
private String status;
#Column(name = "payment_detailID")
private String paymentdetailID;
#Column(name = "date_submitted")
#Temporal(TemporalType.DATE)
private Date dateSubmitted;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "orderTable")
private PaymentDetail paymentDetail;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "orderID")
private Collection<Job> jobCollection;
#JoinColumn(name = "account_no", referencedColumnName = "account_no")
#ManyToOne
private Customer accountNo;
And here is the start of my Job class:
#Entity
#Table(name = "job")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Job.findAll", query = "SELECT j FROM Job j")
, #NamedQuery(name = "Job.findByCode", query = "SELECT j FROM Job j WHERE j.code = :code")
, #NamedQuery(name = "Job.findByJobDescription", query = "SELECT j FROM Job j WHERE j.jobDescription = :jobDescription")
, #NamedQuery(name = "Job.findByPrice", query = "SELECT j FROM Job j WHERE j.price = :price")
, #NamedQuery(name = "Job.findByJobDeadline", query = "SELECT j FROM Job j WHERE j.jobDeadline = :jobDeadline")
, #NamedQuery(name = "Job.findByOrderID", query = "SELECT j FROM Job j WHERE j.orderID = :orderID")})
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "code")
private String code;
#Column(name = "job_description")
private String jobDescription;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "price")
private Float price;
#Column(name = "job_deadline")
#Temporal(TemporalType.DATE)
private Date jobDeadline;
#JoinColumn(name = "orderID", referencedColumnName = "orderID")
#ManyToOne(optional = false)
private OrderTable orderID;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "code")
private Collection<JobLine> jobLineCollection;
Here is the error I'm getting from running this.
[EL Info]: 2018-03-28 15:40:58.826--ServerSession(1692092775)--EclipseLink,
version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2018-03-28 15:40:59.062--ServerSession(1692092775)--file:/E:/Documents/GitHub/Bapers/build/classes/_BapersPU login successful
[EL Warning]: 2018-03-28 15:40:59.139--ServerSession(1692092775)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'payment_detailID' in 'field list'
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'payment_detailID' in 'field list'
Error Code: 1054
Call: SELECT orderID, date_submitted, payment_detailID, special_instructions, status, total_price, account_no FROM order_table WHERE (orderID = ?)
Error Code: 1054
bind => [1 parameter bound]
Query: ReadObjectQuery(name="orderID" referenceClass=OrderTable )
Call: SELECT orderID, date_submitted, payment_detailID, special_instructions, status, total_price, account_no FROM order_table WHERE (orderID = ?)
bind => [1 parameter bound]
Query: ReadObjectQuery(name="orderID" referenceClass=OrderTable )
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:378)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getSingleResult(QueryImpl.java:517)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:400)
at data.DataManagerImpl.findJobByCode(DataManagerImpl.java:127)
at solsoftbapers2.SolSoftBapers2.main(SolSoftBapers2.java:35)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'payment_detailID' in 'field list'
Error Code: 1054
Call: SELECT orderID, date_submitted, payment_detailID, special_instructions, status, total_price, account_no FROM order_table WHERE (orderID = ?)
bind => [1 parameter bound]
Query: ReadObjectQuery(name="orderID" referenceClass=OrderTable )
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:682)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectOneRow(DatasourceCallQueryMechanism.java:714)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectOneRowFromTable(ExpressionQueryMechanism.java:2801)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectOneRow(ExpressionQueryMechanism.java:2754)
at org.eclipse.persistence.queries.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:545)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1168)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1127)
at org.eclipse.persistence.queries.ReadObjectQuery.execute(ReadObjectQuery.java:431)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:3214)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.indirection.NoIndirectionPolicy.valueFromQuery(NoIndirectionPolicy.java:326)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2294)
at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternal(OneToOneMapping.java:1860)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:2144)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1471)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:461)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:1004)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:898)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:851)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:734)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:688)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:795)
at org.eclipse.persistence.queries.ReadObjectQuery.registerResultInUnitOfWork(ReadObjectQuery.java:885)
at org.eclipse.persistence.queries.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:552)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1168)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1127)
at org.eclipse.persistence.queries.ReadObjectQuery.execute(ReadObjectQuery.java:431)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1215)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1751)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
... 4 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'payment_detailID' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.Util.getInstance(Util.java:383)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4208)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4140)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2597)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2758)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2826)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2212)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:1007)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:642)
... 44 more
C:\Users\Daniel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
I'm fairly new to using JPA and databases in Java applications, so I imagine I've made a few small mistakes which are the problem? Any help would be greatly appreciated.
I removed the payment_detailID query as well as annotations and variable declerations related to it, which seemed to fix the issue (payment_detailID wasn't in the OrderTable as a column in the database).
I then found I was getting another error which seemed to be related to how JPA was building SQL statements and that one of my columns was "City/Town". For some reason it really didn't like the "/" being there.
So I renamed the column "city" and now it's working fine.
Related
I'm trying to implement a custom #loader using a namedQuery on a OneToOne - Relation of an entity.
However the lastDatalog field remains null at all given times
I've tested the named query befor on a simple integration test using a repositry, the result was exactly what I intend to have in the lastDestinationStatus
(I need the last updated record from the logs for this data and IREF combination)
when I query the Datalog entity with the id of the data I get the correct result so the Datalog entity seems to be persisted
maybe good to know : curent hibernate version on the project is 4.2.11.Final
this is en extract from entity 1
#Entity
#Table(name = "data")
#NamedQueries({
#NamedQuery(name = "LastLogQuery", query = "select log from DataLog log where log.data.id= ?1 and " +
"log.IREF = (select max(log2.IREF) from DataLog log2 where log2.data = log.data ) " +
"and log.tsUpdate = (select max(log3.tsUpdate) from DataLog log3 where log3.data = log.data and log3.IREF = log.IREF)")})
public class Data{
....
#OneToOne(targetEntity = DataLog.class)
#Loader(namedQuery = "LastLogQuery")
private DataLog lastDataLog;
}
extract from entity 2
#Entity
#Table(name ="log")
public class DataLog{
.......
#ManyToOne(fetch = FetchType.EAGER)
#org.hibernate.annotations.Fetch(value = org.hibernate.annotations.FetchMode.SELECT)
#JoinColumn(name = "DTA_IDN", nullable = false)
private Data data;
/** IREF */
#Column(name = "DSE_LOG_UID_FIL_REF_COD")
private String IREF;
#Column(name = "LST_UPD_TMS", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date tsUpdate;
}
I'm trying to create a Named query with the inner join condition in the Entity class.
However the application is failing to start with an exception.
Entity:
#Entity
#Table(name = "fooentry")
#NamedQuery(name="query1", query="SELECT foo.id, foo.name, foo.type, foo.action, foo.createdDateTime FROM FooEntity foo " +
"INNER JOIN (SELECT name, type, MAX(createdDateTime) AS recenttime FROM FooEntity GROUP BY name, type) recententry " +
"ON (foo.name = recententry.name AND foo.type = recententry.type) AND createdDateTime = recenttime AND isExported = false",
lockMode=PESSIMISTIC_WRITE)
public class FooEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
#NotNull
private String msisdn;
#Column(name = "type")
#NotNull
private String iccid;
#Column(name = "action")
#NotNull
private Long inventoryActionId;
#NotNull
#Column(name = "is_exported")
private Boolean isExported;
#Column(name = "created_date_time")
#NotNull
private LocalDateTime createdDateTime;
//setter and getter
}
Exception:
Application is failing to start with the following exception.
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.HibernateException: Errors in named queries:
query1 failed because of: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 161
You can try query like below. It should return expected result
SELECT foo.id, foo.name, foo.type, foo.action, foo.createdDateTime
FROM FooEntity foo
WHERE
foo.isExported = false AND
EXISTS(
SELECT recententry.name, recententry.type, MAX(recententry.createdDateTime) AS recenttime
FROM FooEntity recententry
WHERE recententry.name = foo.name AND recententry.type = foo.type
GROUP BY recententry.name, recententry.type
HAVING recententry.recenttime = foo.createdDateTime
)
i have a class:
#Entity
#Table(name = "days")
public class DayEntry {
#Expose
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
.
.
#Expose
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable(name = "day_item_hours")
#MapKeyJoinColumn(name = "item_id")
#Column(name = "hours")
private Map<Item, Double> itemsHours;
.
.
}
I need to get from DB all DayEntries which contain specific Item in itemHours field.
I tried:
private final String FIND_BY_ACTIVITY = "from DayEntry d where :activity in index(d.itemsHours)";
#Override
public Collection<DayEntry> findByActivity(Item activity) {
Query query = entityManager.createQuery(FIND_BY_ACTIVITY);
query.setParameter("activity", activity);
return query.getResultList();
}
And get this:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 75 [from ua.siemens.dbtool.model.timesheet.DayEntry d where :activity in index(d.itemsHours)]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 75 [from ua.siemens.dbtool.model.timesheet.DayEntry d where :activity in index(d.itemsHours)]
Not sure how to handle this.
Thanks!
UPDATE
For the moment i ended up with plain SQL Query:
private final String FIND_BY_ACTIVITY = "SELECT * FROM days where id = (SELECT DayEntry_id from day_item_hours where day_item_hours.item_id = :activityId)";
#Override
public Collection<DayEntry> findByActivity(Item activity) {
Query query = entityManager.createNativeQuery(FIND_BY_ACTIVITY_ID, DayEntry.class);
query.setParameter("activityId", activity.getId());
return query.getResultList();
}
but still i wonder how to do it with HQL.
I'm constantly getting error when i wanna insert some data
Project Class
#Entity
#NamedQueries({
#NamedQuery(name = "Project.findAll",
query = "SELECT p FROM Project p"),
#NamedQuery(name = "Project.findByTitle",
query = "SELECT p FROM Project p WHERE p.title = :title")
})
public class Project implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int projectId;
#Column
private String title;
#Column
private String description;
#Column
private Date projectDate;
#ManyToOne
#JoinColumn(name = "projectStatusId")
private ProjectStatus projectStatus;
#OneToMany(mappedBy = "projectMemberId",fetch = FetchType.EAGER)
private List<ProjectMember> memberList = new ArrayList<ProjectMember>();
/**
* Setters and Getters
*/
}
ProjectMember Class
#Entity
#NamedQueries({
#NamedQuery(name = "ProjectMember.findAll",
query = "SELECT pm FROM ProjectMember pm"),
#NamedQuery(name = "ProjectMember.findByProject",
query = "SELECT pm FROM ProjectMember pm WHERE pm.project = :project"),
#NamedQuery(name = "ProjectMember.findByUser",
query = "SELECT pm FROM ProjectMember pm WHERE pm.user = :user"),
#NamedQuery(name = "ProjectMEmeber.findByUserAndProject",
query = "SELECT pm FROM ProjectMember pm WHERE pm.user = :user AND pm.project = :project")
})
public class ProjectMember implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int projectMemberId;
#Column
private Date activationDate;
#Column
private Date lastActiveDate;
#ManyToOne
#JoinColumn(name = "memberStatusId")
private MemberStatus memberStatus;
#ManyToOne
#JoinColumn(name = "projectId")
private Project project;
#ManyToOne
#JoinColumn(name = "memberRoleId")
private MemberRole memberRole;
#ManyToOne
#JoinColumn(name = "userId")
private User user;
/**
* Setter and Getter
*/
}
that's how i run it
ProjectController Class
public String createProject(){
project.setProjectDate(new Date());
project.setProjectStatus(new ProjectStatusFacade().findByStatus("active"));
ProjectMember projectMember = new ProjectMember();
projectMember.setMemberStatus(new MemberStatusFacade().findByStatus("accepted"));
projectMember.setMemberRole(new MemberRoleFacade().findByRole("team leader"));
projectMember.setActivationDate(new Date());
projectMember.setUser(userSession.getUser());
new ProjectFacade().create(project);
System.out.print(project);
projectMember.setProject(project);
new ProjectMemberFacade().create(projectMember);
userSession.setUser(new UserFacade().findById(userSession.getUser().getUserId()));
return "index?faces-redirect=true";
}
and that's what i get in the end
Caused by: javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
... more exceptions
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
... more exceptions
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
...more exceptions
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`goent`.`projectmember`, CONSTRAINT `FKfyw2iinfhhsbrmqbu1sr7l93q` FOREIGN KEY (`projectMemberId`) REFERENCES `project` (`projectId`))
... more exceptions
15:51:06,449 ERROR [io.undertow.request] (default task-4) UT005023: Exception handling request to /hibernate/pages/project-add-member.xhtml: javax.servlet.ServletException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
... more exceptions
Caused by: javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
... more exceptions
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
...more exceptions
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
... more exceptions
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`goent`.`projectmember`, CONSTRAINT `FKfyw2iinfhhsbrmqbu1sr7l93q` FOREIGN KEY (`projectMemberId`) REFERENCES `project` (`projectId`))
... more exceptions
Using: Java, JPA, Hibernate, MySQL5.7
The cause of exception is :
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`goent`.`projectmember`, CONSTRAINT `FKfyw2iinfhhsbrmqbu1sr7l93q` FOREIGN KEY (`projectMemberId`) REFERENCES `project` (`projectId`))
Your action is violating foreign key constraint for projectMemberId column in projectmember table, which is referencing projectId column of project table as per your defined specifications.
This is what most likely is happening.
In the Project entity, you are telling the persistence provider to always eagerly fetch the ProjectNames:
#OneToMany(mappedBy = "projectMemberId",fetch = FetchType.EAGER)
private List<ProjectMember> memberList = new ArrayList<ProjectMember>();
Then in the save method you are creating a ProjectName and populating it with the Project. Thats fine, though the list in the Project does not contain that newly created ProjectName.
The dependency has to be set on both sides, so eventually you would need to do following in your method:
project.getMemberList().add(projectName);
Thank you people, finally I could fix the bug. The problem was in Project class, it was about incorrect mapping. Instead of telling variable to map in other class, I was pointing on PK of that class.
I wrote this
Project class
#ManyToOne
#JoinColumn(name = "projectStatusId")
private ProjectStatus projectStatus;
instead this
//Correct code
#ManyToOne
#JoinColumn(name = "project")
private ProjectStatus projectStatus;
after this change the code started work well.
I am working on an Java/J2EE web application. The persistence of data is made by JPA/TopLink. And I have an issue with this entity :
#Entity
#Table(name = "articlecatalogue_has_article", catalog = "artisance", schema = "public")
#NamedQueries({#NamedQuery(name = "ArticlecatalogueHasArticle.findAll", query = "SELECT a FROM ArticlecatalogueHasArticle a"), #NamedQuery(name = "ArticlecatalogueHasArticle.findByArcIntId", query = "SELECT a FROM ArticlecatalogueHasArticle a WHERE a.articlecatalogueHasArticlePK.arcIntId = :arcIntId"), #NamedQuery(name = "ArticlecatalogueHasArticle.findByArtIntId", query = "SELECT a FROM ArticlecatalogueHasArticle a WHERE a.articlecatalogueHasArticlePK.artIntId = :artIntId"), #NamedQuery(name = "ArticlecatalogueHasArticle.findByAhaDecQuantite", query = "SELECT a FROM ArticlecatalogueHasArticle a WHERE a.ahaDecQuantite = :ahaDecQuantite"), #NamedQuery(name = "ArticlecatalogueHasArticle.findByAhaDecPrixvente", query = "SELECT a FROM ArticlecatalogueHasArticle a WHERE a.ahaDecPrixvente = :ahaDecPrixvente")})
public class ArticlecatalogueHasArticle implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected ArticlecatalogueHasArticlePK articlecatalogueHasArticlePK;
#Column(name = "aha_dec_quantite")
private BigDecimal ahaDecQuantite;
#Column(name = "aha_dec_prixvente")
private BigDecimal ahaDecPrixvente;
#JoinColumn(name = "art_int_id", referencedColumnName = "art_int_id", insertable = false, updatable = false)
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Article article;
#JoinColumn(name = "arc_int_id", referencedColumnName = "arc_int_id", insertable = false, updatable = false)
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Articlecatalogue articlecatalogue;
And the multiple primary keys :
#Embeddable
public class ArticlecatalogueHasArticlePK implements Serializable {
#Basic(optional = false)
#Column(name = "arc_int_id")
private int arcIntId;
#Basic(optional = false)
#Column(name = "art_int_id")
private int artIntId;
When I try to make persistent an ArticlecatalogueHasArticle entity I have this following error :
Local Exception Stack:
Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.1 (Build b60e-fcs (12/23/2008))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne « arc_int_id »
Error Code: 0
Call: INSERT INTO artisance.public.articlecatalogue_has_article (aha_dec_prixvente, aha_dec_quantite, art_int_id, arc_int_id) VALUES (?, ?, ?, ?)
bind => [null, 1, null, null]
Whereas the fields arcIntId and artIntId are not null in the entity which I want to make persistent. I think the problem is due to the double instance of the columns "art_int_id" and "arc_int_id" in the ArticlecatalogueHasArticlePK and in the ArticlecatalogueHasArticle #JoinColumn, but I am not sure and I do not know how to solve the problem.
Any help is appreciated.
Ensure you are setting the id values in the articlecatalogueHasArticlePK, if you do not set them, then they will be null.
You could also remove the articlecatalogueHasArticlePK, and use a IdClass instead of an EmbeddedId. Then you only need to put #Id on your ManyToOne, and don't need any duplicates.
You could also put insertable/updateable false on the basics and true on the ManyToOne if you want to pick the ids up from the relationships.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships
You must use the #MapsId annotation on the two ManyToOne associations.