JPA with Hibernate: .... org.hibernate.QueryException: illegal attempt to dereference collection - sql

I have a #ManyToMany relationship described as follows:
FOO
-----------------------
FOO_ID
........
FOO_BARS
--------------------
BAR_ID
FOO_ID
BAR
--------------------
BAR_ID
.......
#Entity
#Table(name = "FOO")
public class FOO
{
#Id
#SequenceGenerator(....)
#GeneratedValue(...)
#Column(name = "FOO_ID", unique = true, nullable = false, precision = 10)
private int fooId;
public int getFooId()
{
......
}
public void setFooId(final int fooId)
{
......;
}
.....
##ManyToMany()
#JoinTable(name = "FOO_BARS", joinColumns = { #JoinColumn(name = "FOO_ID", nullable = false) }, inverseJoinColumns = { #JoinColumn(name = "BAR_ID", nullable = false) })
private List<Bar> bars;
public List<Bar> getBars()
{
......
}
public void setBars(final List<Bar> bars)
{
......
}
public Bar addBar(Bar value)
{
.....
}
......
}
#Entity
#Table(name = "BAR")
public class Bar
{
#Id
#SequenceGenerator(...)
#GeneratedValue(...)
#Column(name = "BAR_ID", unique = true, nullable = false, precision = 9)
private int barid;
public int getBard()
{
.....
}
public void setBarId(final int barId)
{
.....
}
.....
#ManyToMany(mappedBy = "bar")
private List<Foo> foos;
public List<Foo> getFoos()
{
....
}
public void setFooList(final List<Foo> foos)
{
....
}
public Foo addFoo(final Foo foo)
{
.......
}
.....
}
I have an sql query which I can successfully run to select ALL foos matching a list of provided barIds. This changes according to the provided barIds but is of the format:
SELECT f.* FROM foo f
WHERE
.....
AND f.foo_id IN
(
SELECT fb.foo_id FROM foo_bars fb
WHERE fb.bar_id IN ( 69, 332)
GROUP BY fb.foo_id
HAVING COUNT(DISTINCT fb.bar_id) = 2
);
As entitities don't use a linking table, my issue is in translating this into a query to run using hibernate syntax.
I have tried the following:
SELECT f FROM Foo AS f
WHERE
.....
AND f.fooId IN
(
SELECT b.foos.fooId FROM f.bars b
WHERE b.barid IN (:barids)
GROUP BY b.foos.fooId
HAVING COUNT ( DISTINCT b.barid ) = 2
)
This results in the following error.
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: illegal attempt to dereference collection [bar2_.BAR_ID.foos] with element property reference [fooId]
Any help would be greatly appreciated.

Related

How to call an api and select correct optional from update method in spring mvc

I have been following online tutorials for MVC but have hit a snag with updating.
Have used a updateStudent() method in the controller and pass in the id, but inside the updateStudent() I have alot of optionals.
Trying to figure out how to call the api and select the optional from within the method I want it to use
Any help is appreciated
Thanks.
Controller....
public class StudentController {
public final StudentService studentService;
#Autowired
public StudentController(StudentService studentService) {
this.studentService=studentService;
}
#PutMapping(path="/updateme/{id}")
public void updateStudent(#PathVariable ("id") UUID id,#RequestBody Student student) {
studentService.updateStudent(id, student);
}
StudentService...
#Service
public class StudentService {
private final StudentDao studentDao;
//constructor
public StudentService(#Qualifier("postgres3")StudentDao studentDao) {
this.studentDao=studentDao;
}
#PutMapping
public void updateStudent(UUID id, Student student) {
Optional.ofNullable(student.getChapterProgress())
.filter(cp -> !StringUtils.isEmpty(cp))
.ifPresent(cp -> studentDao.updateChapterProgress(id, cp));
Optional.ofNullable(student.getAvgTestScore())
.filter(avg -> !StringUtils.isEmpty(avg))
.ifPresent(avg -> studentDao.updateAvgTestScore(id, avg));
Optional.ofNullable(student.getChap1Score())
.filter(c1 -> !StringUtils.isEmpty(c1))
.ifPresent(c1 -> studentDao.updateChap1Score(id, c1));
Optional.ofNullable(student.getChap2Score())
.filter(c2 -> !StringUtils.isEmpty(c2))
.ifPresent(c2 -> studentDao.updateChap2Score(id, c2));
Optional.ofNullable(student.getChap3Score())
.filter(c3 -> !StringUtils.isEmpty(c3))
.ifPresent(c3 -> studentDao.updateChap3Score(id, c3));
Optional.ofNullable(student.getChap4Score())
.filter(c4 -> !StringUtils.isEmpty(c4))
.ifPresent(c4 -> studentDao.updateChap4Score(id, c4));
Optional.ofNullable(student.getChap5Score())
.filter(c5 -> !StringUtils.isEmpty(c5))
.ifPresent(c5 -> studentDao.updateChap5Score(id, c5));
Optional.ofNullable(student.getChap6Score())
.filter(c6 -> !StringUtils.isEmpty(c6))
.ifPresent(c6 -> studentDao.updateChap6Score(id, c6));
}
StudentDataAccessService...
#Repository("postgres3")
public class StudentDataAccessService implements StudentDao {
private JdbcTemplate jdbcTemplate;
#Autowired
public StudentDataAccessService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate= jdbcTemplate;
}
#Override
public int updateChapterProgress(UUID id, Integer chapterprogress) {
String sql = "UPDATE student SET chapterprogress = ? WHERE id = ?";
return jdbcTemplate.update(sql, chapterprogress, id);
}
#Override
public int updateAvgTestScore(UUID id, Double avg) {
String sql = "UPDATE student SET avgtestscore = ? WHERE id = ?";
return jdbcTemplate.update(sql, avg, id);
}
#Override
public int updateChap1Score(UUID id, Double chap1Score) {
String sql = "UPDATE student SET chap1score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap1Score, id);
}
#Override
public int updateChap2Score(UUID id, Double chap2Score) {
String sql = "UPDATE student SET chap2score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap2Score, id);
}
#Override
public int updateChap3Score(UUID id, Double chap3Score) {
String sql = "UPDATE student SET chap3score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap3Score, id);
}
#Override
public int updateChap4Score(UUID id, Double chap4Score) {
String sql = "UPDATE student SET chap4score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap4Score, id);
}
#Override
public int updateChap5Score(UUID id, Double chap5Score) {
String sql = "UPDATE student SET chap5score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap5Score, id);
}
#Override
public int updateChap6Score(UUID id, Double chap6Score) {
String sql = "UPDATE student SET chap6score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap6Score, id);
}
#Override
public int updateStudentById(UUID id, Student student) {
return 0;
}
StudentDao...
public interface StudentDao {
int updateStudentById(UUID id,Student student);
int updateChapterProgress(UUID id, Integer chapterprogress);
int updateAvgTestScore(UUID id, Double avg);
int updateChap1Score(UUID id, Double chap1Score);
int updateChap2Score(UUID id, Double chap2Score);
int updateChap3Score(UUID id, Double chap3Score);
int updateChap4Score(UUID id, Double chap4Score);
int updateChap5Score(UUID id, Double chap5Score);
int updateChap6Score(UUID id, Double chap6Score);
Ended up assigning each update to its own method call in the controller, thanks

How can I use WHERE on a ManagedSet?

I have a many-to-many relation, having P, PF and F I want to filter P using F through PF. Like:
final query = Query<P>(context)
..where( (p)=>p.pfSet.firstWhere( (pf)=>pf.f.cod == 1 ).f ).isNotNull();
and the classes:
class P extends ManagedObject<_P> implements _P {}
class _P{
#primaryKey
int cod;
...
ManagedSet<ProdutoFilial> pfSet;
}
class PF extends ManagedObject<_PF> implements _PF {}
class _PF{
#primaryKey
int cod;
#(Relate #pfSet)
P p;
#(Relate #pfSet)
F f;
bool active;
}
class F extends ManagedObject<_F> implements _F {}
class _F{
#primaryKey
int cod;
...
ManagedSet<ProdutoFilial> pfSet;
}
How can I filter this?
Can use a own query that will stay on where:
..predicate = QueryPredicate(
" exists (select f.cod from pf where pf.fcod = #fcod and pf.pcod = p.cod) ",
{ "fcod": 1 });
if you use join in your code query the table name will change.
QueryPredicate is not a very good solution because you cannot set a condition in a joined table (we don't know the aliases of joined tables). I created my own procedure - try it:
QueryExpression<dynamic, dynamic> RelationWhereExt(Query query, List<String> links) {
ManagedEntity e = query.entity;
KeyPath path;
ManagedPropertyDescription property;
links.forEach((link) {
property = e.properties[link];
if (path==null){
// рутовое условие
path = KeyPath(property);
} else {
// следующие условия
path.add(property);
}
if (property is ManagedRelationshipDescription) {
e = (property as ManagedRelationshipDescription).destinationEntity; // меняем entity
}
});
QueryExpression<dynamic, dynamic> queryExpression = QueryExpression<dynamic, dynamic>(path);
(query as MySqlQuery).expressions.add(queryExpression);
return queryExpression;
}
In you case: RelationWhereExt(query, ['pfSet', 'f']).isNotNull();

JPA named query match a list of tuples in IN clause

spring data jpa 1.4.3 with Oracle 11g.
I have an entity like this:
class LinkRecord {
String value;
int linkType;
...
}
I am using (value, linkType) as a composite index.
For a given list of (v, t) tuples, we need to select all the records in the DB so that value = v, linkType = t.
Basically, I want to build this query:
SELECT * FROM LINK_RECORD WHERE (VALUE, LINK_TYPE) IN (('value1', 0), ('value2', 25), ...)
where the list in the IN clause is passed in as a param.
Since we're working with a large volume of data, it would be very undesirable to query for the tuples one by one.
In my repository I've tried this:
#Query("select r from LinkRecord r where (r.value, r.linkType) in :keys")
List<LinkRecord> findByValueAndType(#Param("keys")List<List<Object>> keys);
where keys is a list of (lists of length 2). This gets me ORA_00920: invalid relational operator.
Is there any way to make this work using a named query? Or do I have to resort to native sql?
The answer is too late, but maybe some1 else has the same problem. This is one of my working examples. Here I need to search for all entries that match a given composite key:
The entity....
#Entity
#NamedQueries({
#NamedQuery(name = "Article.findByIdAndAccessId", query = "SELECT a FROM Article a WHERE a.articlePk IN (:articlePks) ORDER BY a.articlePk.article")
})
#Table(name = "ARTICLE")
public class Article implements Serializable
{
private static final long serialVersionUID = 1L;
#EmbeddedId
private ArticlePk articlePk = new ArticlePk();
#Column(name = "art_amount")
private Float amount;
#Column(name = "art_unit")
private String unit;
public Article()
{
}
//more code
}
The PK class....
#Embeddable
public class ArticlePk implements Serializable
{
private static final long serialVersionUID = 1L;
#Column(name = "art_article")
private String article;
#Column(name = "art_acc_identifier")
private Long identifier;
public ArticlePk()
{
}
public ArticlePk(String article, Long identifier)
{
this.article = article;
this.identifier = identifier;
}
#Override
public boolean equals(Object other)
{
if (this == other)
{
return true;
}
if (!(other instanceof ArticlePk))
{
return false;
}
ArticlePk castOther = (ArticlePk)other;
return this.article.equals(castOther.article) && this.identifier.equals(castOther.identifier);
}
#Override
public int hashCode()
{
final int prime = 31;
int hash = 17;
hash = hash * prime + this.article.hashCode();
hash = hash * prime + this.identifier.hashCode();
return hash;
}
//more code
}
Invocation by....
TypedQuery<Article> queryArticle = entityManager.createNamedQuery("Article.findByIdAndAccessId", Article.class);
queryArticle.setParameter("articlePks", articlePks);
List<Article> articles = queryArticle.getResultList();
where....
articlePks is List<ArticlePk>.

HQL generated a incorrect SQL query

I got [42000] You have an error in your SQL syntax error when I execute the HQL below:
update Status set result=18 where (userByUserId.userName like 'administrator')
And this is the corresponding SQL:
update
status cross
join
set
result=18
where
userName like 'administrator'
The results I am getting are incorrect.
But another similar query is in working order:
select count(*) from Status where (userByUserId.userName like 'administrator')
the corresponding SQL:
select
count(*) as col_0_0_
from
status status0_ cross
join
user user1_
where
status0_.userId=user1_.userId
and (
user1_.userName like 'administrator'
)
Does anyone know what happened?
Here is the code(partly):
Status.java
#Table(name = "status")
#Entity
#KeyField("statusId")
public class Status implements Serializable {
private Integer result;
#Column(name = "result", nullable = false, insertable = true, updatable = true
, length = 10, precision = 0)
#Basic
public Integer getResult() {
return result;
}
private Integer userId;
#Column(name = "userId", nullable = false, insertable = true, updatable = true
, length = 10, precision = 0)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
private User userByUserId;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false,
insertable = false, updatable = false)
public User getUserByUserId() {
return userByUserId;
}
}
User.java
#Table(name = "user")
#Entity
#KeyField("userId")
public class User implements Serializable {
private String userName;
#Column(name = "userName", nullable = false, insertable = true, updatable = true, length = 24,
precision = 0, unique = true)
#Basic
public String getUserName() {
return userName;
}
private Collection<Status> statusesByUserId;
#OneToMany(mappedBy = "userByUserId", cascade = CascadeType.ALL)
public Collection<Status> getStatusesByUserId() {
return statusesByUserId;
}
}

Composite primary key with a Foreign key not working in MySQL

My Phone table has a composite primary of phone number and id. id is also a foreign key to the Student table.
I am seeing the below error when I run it.
23:30:28,228 ERROR SqlExceptionHelper:147 - Column 'id' cannot be null
org.hibernate.exception.ConstraintViolationException: could not execute statement
Schema:
Table: student
Columns:
id (PK)
fName
lName
mName
Table: Phone
Columns:
phoneNumber (PK)
color
id(PK)(FK references to Student id)
Student.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
#Entity
#SuppressWarnings("serial")
public class Student implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String fName;
private String lName;
private String mname;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "id")
private Set<Phone> phones;
/**
* #return the fName
*/
public String getfName() {
return fName;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #return the lName
*/
public String getlName() {
return lName;
}
/**
* #return the mname
*/
public String getMname() {
return mname;
}
/**
* #return the phones
*/
public Set<Phone> getPhones() {
return phones;
}
/**
* #param fName
* the fName to set
*/
public void setfName(final String fName) {
this.fName = fName;
}
/**
* #param id
* the id to set
*/
public void setId(final int id) {
this.id = id;
}
/**
* #param lName
* the lName to set
*/
public void setlName(final String lName) {
this.lName = lName;
}
/**
* #param mname
* the mname to set
*/
public void setMname(final String mname) {
this.mname = mname;
}
/**
* #param phones
* the phones to set
*/
public void setPhones(final Set<Phone> phones) {
this.phones = phones;
}
}
Phone.java
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#IdClass(PhonePK.class)
#Entity
#SuppressWarnings("serial")
public class Phone implements Serializable {
#Id
private String phoneNumber;
// #Id
// #ManyToOne
// #JoinColumn(name = "id", insertable = false, updatable = false)
// private String id;
#Id
#ManyToOne
#JoinColumn(name = "id", insertable = false, updatable = false)
private Student student;
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
private String color;
/**
* #return the color
*/
public String getColor() {
return color;
}
/**
* #return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* #return the student
*/
public Student getStudent() {
return student;
}
/**
* #param color
* the color to set
*/
public void setColor(final String color) {
this.color = color;
}
/**
* #param phoneNumber
* the phoneNumber to set
*/
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* #param student
* the student to set
*/
public void setStudent(final Student student) {
this.student = student;
}
}
PhonePK.java
import java.io.Serializable;
#SuppressWarnings("serial")
public class PhonePK implements Serializable {
private String phoneNumber;
//private String id;
private Student student;
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
/**
* #return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* #return the student
*/
public Student getStudent() {
return student;
}
/**
* #param phoneNumber
* the phoneNumber to set
*/
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* #param student
* the student to set
*/
public void setStudent(final Student student) {
this.student = student;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PhonePK other = (PhonePK) obj;
if (phoneNumber == null) {
if (other.phoneNumber != null) {
return false;
}
} else if (!phoneNumber.equals(other.phoneNumber)) {
return false;
}
if (student == null) {
if (other.student != null) {
return false;
}
} else if (!student.equals(other.student)) {
return false;
}
// if (id == null) {
// if (other.id != null) {
// return false;
// }
// } else if (!id.equals(other.id)) {
// return false;
// }
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
result = prime * result + ((student == null) ? 0 : student.hashCode());
// result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">pwd</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
Main.java
import java.util.LinkedHashSet;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(final String args[]) {
Configuration configuration = new Configuration();
Transaction transaction = null;
configuration.addAnnotatedClass(Student.class);
configuration.addAnnotatedClass(Phone.class);
configuration.addAnnotatedClass(PhonePK.class);
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
System.out.println("Session Factory!!!!" + sessionFactory);
Session session = sessionFactory.openSession();
Student student = new Student();
student.setfName("Bob");
student.setlName("Buster");
Set<Phone> phones = new LinkedHashSet<Phone>();
Phone ph1 = new Phone();
ph1.setColor("Black");
ph1.setPhoneNumber("1111111111");
Phone ph2 = new Phone();
ph2.setColor("Blue");
ph2.setPhoneNumber("2222222222");
phones.add(ph1);
phones.add(ph2);
student.setPhones(phones);
try {
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Console output:
23:30:24,291 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
23:30:24,296 DEBUG SQL:104 - alter table Phone drop foreign key
FK_aoj0eivd0ap3drxnoyk4xj10q
23:30:25,613 DEBUG SQL:104 - drop table if exists Phone
23:30:25,967 DEBUG SQL:104 - drop table if exists Student
23:30:26,230 DEBUG SQL:104 - create table Phone (phoneNumber varchar(255) not null,
color varchar(255), id integer not null, primary key (phoneNumber, id))
23:30:26,731 DEBUG SQL:104 - create table Student (id integer not null auto_increment,
fName varchar(255), lName varchar(255), mname varchar(255), primary key (id))
23:30:26,792 DEBUG SQL:104 - alter table Phone add index FK_aoj0eivd0ap3drxnoyk4xj10q
(id), add constraint FK_aoj0eivd0ap3drxnoyk4xj10q foreign key (id) references Student
(id)
23:30:27,352 INFO SchemaExport:405 - HHH000230: Schema export complete
Session Factory!!!!org.hibernate.internal.SessionFactoryImpl#548997d1
23:30:27,823 DEBUG SQL:104 - insert into Student (fName, lName, mname) values (?, ?, ?)
23:30:27,886 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - Bob
23:30:27,887 TRACE BasicBinder:84 - binding parameter [2] as [VARCHAR] - Buster
23:30:27,888 TRACE BasicBinder:72 - binding parameter [3] as [VARCHAR] - <null>
23:30:28,005 DEBUG SQL:104 - select phone_.phoneNumber, phone_.id, phone_.color as
color2_0_ from Phone phone_ where phone_.phoneNumber=? and phone_.id=?
23:30:28,009 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - 1111111111
23:30:28,010 TRACE BasicBinder:72 - binding parameter [2] as [INTEGER] - <null>
23:30:28,102 DEBUG SQL:104 - select phone_.phoneNumber, phone_.id, phone_.color as
color2_0_ from Phone phone_ where phone_.phoneNumber=? and phone_.id=?
23:30:28,103 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - 2222222222
23:30:28,104 TRACE BasicBinder:72 - binding parameter [2] as [INTEGER] - <null>
23:30:28,222 DEBUG SQL:104 - insert into Phone (color, phoneNumber, id) values (?, ?,
?)
23:30:28,223 TRACE BasicBinder:84 - binding parameter [1] as [VARCHAR] - Black
23:30:28,224 TRACE BasicBinder:84 - binding parameter [2] as [VARCHAR] - 1111111111
23:30:28,224 TRACE BasicBinder:72 - binding parameter [3] as [INTEGER] - <null>
23:30:28,227 WARN SqlExceptionHelper:145 - SQL Error: 1048, SQLState: 23000
23:30:28,228 ERROR SqlExceptionHelper:147 - Column 'id' cannot be null
org.hibernate.exception.ConstraintViolationException: could not execute statement
at
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert
(SQLExceptionTypeDelegate.java:74)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert
(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert
(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert
(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate
(ResultSetReturnImpl.java:136)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch
(NonBatchingBatch.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert
(AbstractEntityPersister.java:3067)
at org.hibernate.persister.entity.AbstractEntityPersister.insert
(AbstractEntityPersister.java:3509)
at org.hibernate.action.internal.EntityInsertAction.execute
(EntityInsertAction.java:88)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:286)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions
(AbstractFlushingEventListener.java:339)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush
(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.
beforeTransactionCommit
(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit
(AbstractTransactionImpl.java:175)
at Main.main(Main.java:49)
Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'id' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate
(ResultSetReturnImpl.java:133)
... 14 more
23:30:28,323 INFO AbstractBatchImpl:195 - HHH000010:
On release of batch it still contained JDBC statements
you can create embeddale Primary key class.
#Embeddable
public class Phone_pk implements Serializable{
#ManyToOne(targetEntity=Student.class)
#JoinColumn(name="id", referencedColumnName="id")
#ForeignKey(name="Student_Phone_FK")
private Student student;
private String phoneNumber;
}
And use this as primary key in your phone class
#EmbeddedId
private Phone_pk PK;