EclipseLink JPA CriteriaBuilder generated invalid SQL Syntax - jpa-2.0

I have two objects, both defined as entities, one containing the other as follows:
#Entity
public class TestC
{
#Id #GeneratedValue
private Integer id;
#ManyToOne (cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
TestD d;
}
#Entity
public class TestD
{
#Id #GeneratedValue
private Integer id;
String moo;
}
The entities are persisted:
TestC c2 = new TestC();
TestD d2 = new TestD();
d2.moo = "d2";
c2.d = d2;
em.getTransaction().begin();
em.persist(d2);
em.persist(c2);
em.getTransaction().commit();
I am trying to query for TestC objects with an instance of TestD:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<TestC> query = builder.createQuery(TestC.class);
Root<TestC> from = query.from(TestC.class);
ParameterExpression<TestD> pe = builder.parameter(TestD.class);
query.where(builder.equal(pe, from.<TestD>get("d")));
TestC found = em.createQuery(query)
.setParameter(pe, d2)
.getSingleResult();
But EclipseLink kicks out the following error when running the query (note the SQL is invalid near "(? = )", there is no column name for the TestD object):
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Invalid argument value: java.io.NotSerializableException
Error Code: 0
Call: SELECT t1.ID, t1.D_ID FROM TESTD t0, TESTC t1 WHERE ((? = ) AND (t0.ID = t1.D_ID))
bind => [1 parameter bound]
Query: ReadAllQuery(referenceClass=TestC sql="SELECT t1.ID, t1.D_ID FROM TESTD t0, TESTC t1 WHERE ((? = ) AND (t0.ID = t1.D_ID))")
Am I building the query wrong?
Thanks for any help!

It is not documented in the JavaDoc, but ParameterExpression should be second argument. Order follows same logic as equal(Expression x, java.lang.Object y). Additionally you need .select. EclipseLink (at least 2.3.0) works also without, but according specification leaving select/multiselect out is not portable:
Portable applications should use the select or multiselect method to
specify the query’s selection list. Applications that do not use one
of these methods will not be portable.
After those changes, correct approach is:
CriteriaQuery<TestC> query = builder.createQuery(TestC.class);
Root<TestC> from = query.from(TestC.class);
ParameterExpression<TestD> pe = builder.parameter(TestD.class);
query.select(from)
.where(builder.equal(from.<TestD>get("d"), pe));
TestC found = em.createQuery(query)
.setParameter(pe, d)
.getSingleResult();

Related

JPQL left Join and Criteria API joins (Left and inner) throwing extra db queries to initialise associations

I am having below two entities .Instructor entity has relationship oneToMany with Vehicle entity.
public class Instructor {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
#GenericGenerator(name = "native", strategy = "native")
private int id;
#Version
#Column(columnDefinition = "int(11) not null default 0")
private int version = 0;
#OneToMany(mappedBy = "instructor", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<Vehicle> vehicles = new HashSet<>();
.....
public class Vehicle {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator =
"native")
#GenericGenerator(name = "native", strategy = "native")
private int id;
#ManyToOne(fetch = FetchType.LAZY)
private Student student;
#ManyToOne(fetch = FetchType.LAZY)
private Instructor instructor;
I want to fetch all instructors along with their vehicles in one query .
I have tried below four ways for doing this but i am not able to do this with test case 2 , 3 and 4 .
Test Case 1 : With JPQL join fetch clause.
#Test
#Transactional
#Rollback(false)
public void fetchTest1(){
List<Instructor> instructorsJpqlJoinFetch = em
.createQuery("select distinct i from
Instructor i join fetch i.vehicles v ",
Instructor.class)
.getResultList();
print(instructorsJpqlJoinFetch);
}
private void print(List<Instructor> instructors) {
instructors.forEach(i -> {
System.out.println("######Instructor Name : " + i.getName());
i.getVehicles().forEach(v -> {
System.out.println("######Instructor Vehicle
Number : " + v.getVehicleNumber());
});
});
Db Query gone to DB for case 1 :
select
distinct instructor0_.id as id1_2_0_,
vehicles1_.id as id1_5_1_,
instructor0_.address as address2_2_0_,
instructor0_.birth_date_time as birth_da3_2_0_,
instructor0_.birth_date_time_zone_offset as birth_da4_2_0_,
instructor0_.created_date as created_5_2_0_,
instructor0_.day_off_time as day_off_6_2_0_,
instructor0_.day_start_time as day_star7_2_0_,
instructor0_.father_name as father_n8_2_0_,
instructor0_.mother_name as mother_n9_2_0_,
instructor0_.name as name10_2_0_,
instructor0_.photo as photo11_2_0_,
instructor0_.monthly_salary as monthly12_2_0_,
instructor0_.updated_date as updated13_2_0_,
instructor0_.version as version14_2_0_,
vehicles1_.creation_date as creation2_5_1_,
vehicles1_.instructor_id as instruct8_5_1_,
vehicles1_.purchased_date_time as purchase3_5_1_,
vehicles1_.purchased_date_zone_offset as purchase4_5_1_,
vehicles1_.student_id as student_9_5_1_,
vehicles1_.updated_date as updated_5_5_1_,
vehicles1_.vechicle_type as vechicle6_5_1_,
vehicles1_.vehicle_number as vehicle_7_5_1_,
vehicles1_.instructor_id as instruct8_5_0__,
vehicles1_.id as id1_5_0__
from
instructor instructor0_
inner join
vehicle vehicles1_
on instructor0_.id=vehicles1_.instructor_id
As a result All instructors are fethched from db along with their vehicles
and after executing i.getVehicles() no query goes to db again . Which should be a correct behaviour . I am getting this behaviour with JPQL join fetch clause .
Test Case 2 : Tried same with Criteria API like below :
#Test
#Transactional
#Rollback(false)
public void fetchTest3() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Instructor> cq =
cb.createQuery(Instructor.class);
Root<Instructor> root = cq.from(Instructor.class);
root.join(Instructor_.vehicles);
List<Instructor> instructorsWithCriteria =
em.createQuery(cq.distinct(true).select(root)).
getResultList();
print(instructorsWithCriteria);
}
Db query gone to db for case 2 :
select distinct instructor0_.id as id1_2_,
instructor0_.address as address2_2_,
instructor0_.birth_date_time as birth_da3_2_,
instructor0_.birth_date_time_zone_offset as birth_da4_2_,
instructor0_.created_date as created_5_2_,
instructor0_.day_off_time as day_off_6_2_,
instructor0_.day_start_time as day_star7_2_,
instructor0_.father_name as father_n8_2_,
instructor0_.mother_name as mother_n9_2_,
instructor0_.name as name10_2_,
instructor0_.photo as photo11_2_,
instructor0_.monthly_salary as monthly12_2_,
instructor0_.updated_date as updated13_2_,
instructor0_.version as version14_2_
from
instructor instructor0_
inner join
vehicle vehicles1_
on instructor0_.id=vehicles1_.instructor_id
**As a result all instructors are fethched from db . As soon as i hit
i.getVehciles() in print method a query to get vehicles of this instructor goes to db . Same happens for all instructors one by one .
Same behaviour happens for case 3 and 4 below too .
What should be passed in select clause of case 2, 3, 4 so that vehicle columns also got selected in query ?
**
Test case 3: JPQL left join
#Test
#Transactional
#Rollback(false)
public void fetchTest2() {
List<Instructor> instructorsJpqlLeftJoin = em
.createQuery("select distinct i from Instructor i left join
i.vehicles v ", Instructor.class)
.getResultList();
print(instructorsJpqlLeftJoin);
}
Db Query to db for Case 3 :
select
distinct instructor0_.id as id1_2_,
instructor0_.address as address2_2_,
instructor0_.birth_date_time as birth_da3_2_,
instructor0_.birth_date_time_zone_offset as birth_da4_2_,
instructor0_.created_date as created_5_2_,
instructor0_.day_off_time as day_off_6_2_,
instructor0_.day_start_time as day_star7_2_,
instructor0_.father_name as father_n8_2_,
instructor0_.mother_name as mother_n9_2_,
instructor0_.name as name10_2_,
instructor0_.photo as photo11_2_,
instructor0_.monthly_salary as monthly12_2_,
instructor0_.updated_date as updated13_2_,
instructor0_.version as version14_2_
from
instructor instructor0_
left outer join
vehicle vehicles1_
on instructor0_.id=vehicles1_.instructor_id
Case 4 : Criteria API Left Join :
#Test
#Transactional
#Rollback(false)
public void fetchTest4() {
CriteriaBuilder cbLeftJoin = em.getCriteriaBuilder();
CriteriaQuery<Instructor> cqLeftJoin =
cbLeftJoin.createQuery(Instructor.class);
Root<Instructor> rootLeftJoin = cqLeftJoin.from(Instructor.class);
rootLeftJoin.join(Instructor_.vehicles, JoinType.LEFT);
List<Instructor> instructorsWithCriteriaLeftJoin = em
.createQuery(cqLeftJoin.distinct(true).
select(rootLeftJoin)).getResultList();
print(instructorsWithCriteriaLeftJoin);
}
Db Query for case 4 :
select
distinct instructor0_.id as id1_2_,
instructor0_.address as address2_2_,
instructor0_.birth_date_time as birth_da3_2_,
instructor0_.birth_date_time_zone_offset as birth_da4_2_,
instructor0_.created_date as created_5_2_,
instructor0_.day_off_time as day_off_6_2_,
instructor0_.day_start_time as day_star7_2_,
instructor0_.father_name as father_n8_2_,
instructor0_.mother_name as mother_n9_2_,
instructor0_.name as name10_2_,
instructor0_.photo as photo11_2_,
instructor0_.monthly_salary as monthly12_2_,
instructor0_.updated_date as updated13_2_,
instructor0_.version as version14_2_
from
instructor instructor0_
left outer join
vehicle vehicles1_
on instructor0_.id=vehicles1_.instructor_id
What should i do in case 2,3,4 so that vehicles columns also got selected in the same query so that no secondory selects go to db?

JPA - Unidirectional relationship containing List with duplicate entries

I have two entities, TestCase and TestCaseStep, defined as follows:
TestCase
#Entity
#Table(name = "TEST_CASE")
public class TestCase implements Serializable, TestCase
{
#Id
#Column(name = "name")
private String name;
#OneToMany(fetch = FetchType.EAGER)
#JoinTable(name = "Testcase_Step_Association", joinColumns = { #JoinColumn(name = "TC_NAME", referencedColumnName = "NAME") }, inverseJoinColumns = {
#JoinColumn(name = "STEP_NAME", referencedColumnName = "NAME") })
#OrderColumn(name = "STEP_NUMBER", nullable = false)
private List<TestCaseStep> testCaseSteps;
[...]
}
TestCaseStep
#Entity
#Table(name = "TEST_CASE_STEPS")
public class TestCaseStep implements Serializable, TestCaseStep
{
#Id
#Column(name = "name")
private String name;
[...]
}
This works fine as long as I do not try to insert the same object into the list of test case steps more than once. As soon as I try that, I get a primary key violation:
Caused by: org.h2.jdbc.JdbcSQLException: Eindeutiger Index oder Prim�rschl�ssel verletzt: "PRIMARY_KEY_9 ON PUBLIC.TESTCASE_STEP_ASSOCIATION(TC_NAME, TESTCASESTEPS_NAME) VALUES ('TESTCASE_1', 'OUT_STEP', 395)"
Unique index or primary key violation: "PRIMARY_KEY_9 ON PUBLIC.TESTCASE_STEP_ASSOCIATION(TC_NAME, TESTCASESTEPS_NAME) VALUES ('TESTCASE_1', 'OUT_STEP', 395)"; SQL statement:
INSERT INTO Testcase_Step_Association (testCaseSteps_NAME, TC_NAME, STEP_NUMBER) VALUES (?, ?, ?) [23505-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.index.BaseIndex.getDuplicateKeyException(BaseIndex.java:107)
at org.h2.mvstore.db.MVSecondaryIndex.checkUnique(MVSecondaryIndex.java:230)
at org.h2.mvstore.db.MVSecondaryIndex.add(MVSecondaryIndex.java:189)
at org.h2.mvstore.db.MVTable.addRow(MVTable.java:704)
at org.h2.command.dml.Insert.insertRows(Insert.java:156)
at org.h2.command.dml.Insert.update(Insert.java:114)
at org.h2.command.CommandContainer.update(CommandContainer.java:98)
at org.h2.command.Command.executeUpdate(Command.java:258)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:125)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:892)
... 193 more
I need to allow my users to repeat the same test case step multiple times. How can I accomplish this without using a separate entity to map the relationship by myself?
Instead of defining name as a primary key in both TestCase and TestCaseSteps Entity,try to define a Surrogate Key as a primary key wherein you keep the Generation Strategy of that Surrogate Key to AUTO
In this way ,you always make a new Insert when you are rerunning test cases.

List of instances with minimal date of their group

I'm working on a Java project, using Hibernate to administrate data on a SQL database.
I try to fetch a list of instances from the Database, that have a minimal timestamp of the group they share. The group is modeled by a container.
Here is a minimal model sketch:
#Entity
#Table(name = "object")
public class Object implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.Auto)
long obj_id;
#Column(name = "time_stamp", nullable = false)
Date timestamp;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "container_id", nullable = false)
Container con;
}
#Entity
#Table(name = "container")
public class Container{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
long con_id;
#OneToMany(mappedBy = "container")
List<object> obj_list;
}
So there are some objects with a timestamp and containers that group these objects.
For example, there are two containers, con_a and con_b:
Container con_a:
con_id = 1
obj_list = {obj_a, obj_b}
Container con_b:
con_id = 2
obj_list = {obj_c}
And three objects, obj_a, obj_b, obj_c:
Object obj_a
obj_id = 1
timestamp = 10
con = con_a
Object obj_b
obj_id = 2
timestamp = 20
con = con_a
Object obj_c
obj_id = 3
timestamp = 30
con = con_b
The desired List in this example would look like:
List<Object> = {obj_a, obj_c}
I seem to move in a circle, as I do not even know where to "start" the query:
Criteria crit = session.createCriteria(Container.class). ...
or
Criteria crit = session.createCriteria(Object.class). ...
It seems both possible for me, but i just have no idea how to go on from any of those 2 possibilities.
Update [2014.07.11, 14:19]:
I tried and started the query with the Object class and used a Subquery:
Session session = getSession();
Transaction transaction = session.beginTransaction();
DetachedCriteria IdListOfGroupMinimum = DetachedCriteria.forClass(Object.class, "obj")
IdListOfGroupMinimum.createAlias("con.id", "containerId")
.setProjection(
.Projections.projectionList()
.add(Projections.property("obj.id"))
.add(Projections.min("obj.timestamp"))
.add(Projections.groupProperty("containerId")))
.setProjection(Projection.property("obj.id"));
Criteria objects = session.createCriteria(object.class, "obj")
objects.add(Subqueries.in("obj.id", IdListOfGroupMinimum));
List<Object> = objects.list();
But I received the following error:
javax.servlet.ServletException: org.hibernate.QueryException: not an association: id
I tried to do this:
SELECT * from Object
WHERE id IN (
SELECT obj.id
FROM Object obj
INNER JOIN (
SELECT obj.containerID, MIN(obj.timestamp) AS minimum
FROM Object obj
GROUP BY obj.containerID) subquery
ON obj.containerID = subquery.containerID
WHERE obj.timestamp = subquery.minimum
)
I found a solution for my problem which is probably not the most elegant one, but it works.
Mainly I used the SQL-Query that I already posted above:
Session session = getSession();
Transaction transaction = session.beginTransaction();
//This query fetches the IDs of the smallest objects in each group with
//regard to the timestamp
Query q = session.createSQLQuery(
"SELECT obj.id FROM Object obj "
+ "INNER JOIN ( "
+ "SELECT obj.containerID, MIN(obj.timestamp) AS minimum "
+ "FROM Object obj "
+ "GROUP BY obj.containerID) subquery "
+ "ON obj.containerID = subquery.containerID "
+ "WHERE obj.timestamp = subquery.minimum "
);
//This tells Hibernate that the result are values of type Long
q.addScalar("id", LongType.INSTANCE)
//Creates a list of the found IDs
#SuppressWarnings("unchecked")
List<Long> ids = q.list();
//Fetches all object with those IDs...
Criteria smallestOfEachGroup = session.createCriteria(Object.class)
.add(Restrictions.in("id", ids);
//...and saves them in a list.
#SuppressWarnings("unchecked")
List<Object> desiredList = smallestOfEachGroup.list()
try{
transaction.commit();
} catch(HibernateException e) {
transaction.rollback();
}
As all my sketches are not the real code, so there might be still naming errors.
Anyway, I hope this helps someone.
I still would be pleased by any more elegant solution.
Update [2014.07.20, 18:50]:
I found a solution that uses Hibernate Criteria exclusively :)
Session session = getSession();
Transaction transaction = session.beginTransaction();
//This subquery fetches the minimal timestamp of a container.
DetachedCriteria minOfGroup = DetachedCriteria.forClass(Object.class);
minOfGroup.add(Restrictions.eqProperty("con.con_id", "outerObject.con.con_id")
.setProjection(Projections.min("timestamp"));
//This subquery fetches the IDs of all Objects, whose timestamp is minimal
//in their container.
DetachedCriteria groupwiseMin = DetachedCriteria.forClass(Object.class, "outerObject");
groupwiseMin.add(Subqueries.propertyEq("timestamp", minOfGroup));
.setProjections(Projections.id())
//This subquery fetches all Objects whose IDs are fetched by the groupwiseMin
//query
Criteria groupwiseMinObjects = session.createCriteria(Object.class);
groupwiseMinObjects.add(Subqueries.propertyIn("obj_id", groupwiseMin));
List<Object> desiredObjects = groupwiseMinObjects.list();
try{
transaction.commit();
} catch(HibernateException e) {
transaction.rollback();
}
I think you can make this query even shorter, if you remove the groupwiseMinObjects query above replace the groupwiseMin query by:
Criteria anotherGroupWiseMinObjects = session.createCriteria(Object.class, "outerObject");
anotherGroupwiseMinObjects.add(Subqueries.propertyEq("timestamp", minOfGroup));
But I did not test that.
In my original project I use several subqueries that converge in a single query.
That means after some subqueries, there is a final query like:
Criteria finalQuery = session.createCriteria(Object.class);
finalQuery.add(Subqueries. (...) )
(...)
.add(Subqueries. (...) );

count * with where clause using JPA criteria query

I want to find records for related_elements table, where relationId belongs to a list
suppose a Set tempSet contains[2,3,4]
I have to check for these value contains in related_element table using jpa criteria query
CriteriaBuilder cb1=entityManager.getCriteriaBuilder();
CriteriaQuery<RelatedElements> cq1=cb1.createQuery(RelatedElements.class);
Root<RelatedElements> RelatedElementsRoot=cq1.from(RelatedElements.class);
for (Integer tSet : tempSet) {
ParameterExpression<Integer> pRelatedElement=cb1.parameter(Integer.class);
cq1.multiselect(cb1.count(RelatedElementsRoot.<RelatedElements>get("relatedElementsPk").<Integer>get("relationId"))).where(cb1.equal(RelatedElementsRoot.get("relationId"), pRelatedElement));
TypedQuery<RelatedElements> qry = entityManager.createQuery(cq1);
qry.setParameter(pRelatedElement, tSet);
count = entityManager.createQuery(cq1).getSingleResult().getRelationId();
}
but its now working...any suggessions
second try
CriteriaBuilder cb1=entityManager.getCriteriaBuilder();
CriteriaQuery<Integer> cq1 = cb1.createQuery(Integer.class);
Root<RelatedElements> RelatedElementsRoot=cq1.from(RelatedElements.class);
for (Integer tSet : tempSet) {
ParameterExpression<Integer> pRelatedElement=cb1.parameter(Integer.class);
cq1.multiselect(cb1.count(cq1.from(RelatedElements.class)));
cq1.where((cb1.equal(RelatedElementsRoot.get("relatedElementsPk").get("relationId"), pRelatedElement)));
TypedQuery<Integer> qry = entityManager.createQuery(cq1);
qry.setParameter(pRelatedElement, tSet);
count =qry.getSingleResult();
}
its giving exception at qry.setParameter
Unable to locate appropriate constructor on class [java.lang.Integer] [select new java.lang.Integer(count(*)) from com.mcd.webex.model.RelatedElements as generatedAlias0, com.mcd.webex.model.RelatedElements as generatedAlias1 where generatedAlias0.relatedElementsPk.relationId=:param0]
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<Dzialy> root = cq.from(Dzialy.class);
EntityType <Dzialy> Dzialy_ = root.getModel();
cq.select((cb.countDistinct(root)));
cq.where( cb.equal( root.get(Dzialy_.getSingularAttribute("DZI_id")), 1) );
long l = em.createQuery(cq).getSingleResult();
em - EntityManager
DZI_id - column name
1 - searching value
Dzialy - entity class
As documented, CriteriaBuilder.count returns Expression<java.lang.Long>. Consequently type argument to CriteriaQuery and TypedQuery should be Long as well. Same holds true for type of count variable.
When there is only one value to be selected, then it makes sense to use CriteriaQuery.select instead of multiselect, because then such an error is catched already in compile time.
Long count;
...
CriteriaQuery<Long> cq1 = cb1.createQuery(Long.class);
...
cq1.select(cb1.count(cq1.from(RelatedElements.class)));
...
TypedQuery<Long> qry = entityManager.createQuery(cq1);
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(YourEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();

Unexpected behaviour of EntityManager.merge()

I am using embedded glassfish (3.1.2.2) with junit (4.11), with JDK 1.7, though my source and target is set to 1.6 (maven-compiler-plugin configuration).
Following is my code:
Person.java
#Entity
public class Person implements Serializable {
private static final long serialVersionUID = 81398385247591972L;
#Id
#GeneratedValue
private Long id;
#Version
private Long version;
#Column(length = 15, nullable = false, unique = true, updatable = false)
private String username;
#Column(length = 50)
private String status;
// Constructors
// getters/setters
// hashCode, equals, toString
}
Service.java
#Stateless
public class Service {
#PersistenceContext(unitName = "ExamplePU", type = PersistenceContextType.TRANSACTION)
private EntityManager em;
public Person add(Person person) {
em.persist(person);
return person;
}
public Person find(Long id) {
return em.find(Person.class, id);
}
public Person modify(Person person) {
return em.merge(person);
}
// some more code ...
}
ServiceTest.java
public class ServiceTest {
private static EJBContainer ejbContainer;
private static Service service;
// #BeforeClass, #AfterClass, #Before, #After
#Test
public void testMerge() {
Person person;
/* Step 1 */person = service.add(new Person("username", "status"));
print("Added : " + person);
person.setStatus("Away");
/* Step 2 */person = service.modify(person);
print("Merged (status change) : " + person);
person.setUsername("UsErNaMe");
/* Step 3 */person = service.modify(person);
print("Merged (username change) : " + person);
}
// Some more tests
}
Step 1 generates following SQL (as expected):
INSERT INTO PERSON (ID, STATUS, USERNAME, VERSION) VALUES (?, ?, ?, ?)
bind => [1, status, username, 1]
Step 2 generates following SQL (as expected):
UPDATE PERSON SET STATUS = ?, VERSION = ? WHERE ((ID = ?) AND (VERSION = ?))
bind => [Away, 2, 1, 1]
Step 3 does not generate any SQL, but it does not throw any exception, which I am expecting, as the 'username' is annotated as #Column(..., updatable = false). The print(...) method prints following output:
Merged (username change) : Person [id=1, version=2, username=UsErNaMe, status=Away]
This time the merge() operation has updated username, but not version. Also, now the database is out-of-sync with EntityManager cache.
Is this expected, or bug in EclipseLink?
UPDATE
Expected result is exception at Step 3 above.
UPDATE
Have filed bug here.
You marked the column as non-updatable, and EclipseLink detects that the only change made to the person you tell it to merge is the user name. But the user name must not be updated. So it doesn't issue any SQL update query.
If you mark a column as non-updatable, you shouldn't update it.
So, to make things clear, the behavior you observe is the expected behavior.