com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null? - java

im having difficulty inserting datas to database table from java classes. I'm getting "Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null"... I did some digging and couldn't figure it out. Let me post my codes... before that i explain what i want to do... This project contains Servlet class,JSP , and java classes. I'm using JSP html Form to get datas and records them to into a database. Codes here...
#Entity
#Table(name="\"Leave\"")
public class Leave implements Serializable{
/**
*
*/
private static final long serialVersionUID = 9088190714759727299L;
#Id
#Column(name="id",nullable=false,updatable=false)
private Long id;
//#OneToOne(mappedBy=)
#GeneratedValue(strategy = GenerationType.AUTO)
#JoinColumn(name = "person_id",referencedColumnName="id")
private Person person;
//#Enumerated(LeaveType)
#Column(name="leavetype")
private LeaveType leavetype;
#Temporal(TemporalType.DATE)
#Column(name="prepdate")
private Date prepdate;
#Temporal(TemporalType.DATE)
#Column(name="startdate")
private Date startdate;
#Temporal(TemporalType.DATE)
#Column(name="enddate")
private Date enddate;
#Temporal(TemporalType.DATE)
#Column(name="oldstartdate")
private Date oldStartdate;
#Temporal(TemporalType.DATE)
#Column(name="oldenddate")
private Date oldEnddate;
#Column(name="workday")
private String workday;
#Column(name="calendarday")
private String calendarday;
#Column(name="reason")
private String reason;
getters setters....
#Entity
#Table(name="\"Person\"")
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2532993385565282772L;
#Id
#Column(name="id",nullable=false,updatable=false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String surname;
private String sskno;
private String workstartdate;
private String address;
private String telno;
#OneToMany
private List<Leave> leaves;
AND MY SERVLET CLASS IS....
#WebServlet("/LeaveServlet")
public class LeaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNIT_NAME = "EmployeeLeaveForm";
private static EntityManagerFactory emf;
public LeaveServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager entityManager = emf.createEntityManager();
try {
PrintWriter out = response.getWriter();
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/FormInterface.jsp");
Person person = new Person();
Leave leave = new Leave();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String choosenType = request.getParameter("leavetype");
// LEAVING
// TYPES---------------------------------------------------------------------------------------------------
if (choosenType == null) {
request.setAttribute("leaveTypeError",
"Izin turunu giriniz.");
requestDispatcher.forward(request, response);
return;
}
else if (choosenType.equals(LeaveType.ANNUAL.toString())) {
leave.setLeavetype(LeaveType.ANNUAL);
} else if (choosenType.equals(LeaveType.MARRIAGE.toString())) {
leave.setLeavetype(LeaveType.MARRIAGE);
} else if (choosenType.equals(LeaveType.FEEDING.toString())) {
leave.setLeavetype(LeaveType.FEEDING);
} else if (choosenType.equals(LeaveType.MEDICAL.toString())) {
leave.setLeavetype(LeaveType.MEDICAL);
} else if (choosenType.equals(LeaveType.MATERNITY.toString())) {
leave.setLeavetype(LeaveType.MATERNITY);
} else if (choosenType.equals(LeaveType.OTHER.toString())) {
leave.setLeavetype(LeaveType.OTHER);
leave.setReason(request.getParameter("reason"));
if (leave.getReason() != null) {
} else if (leave.getReason() == null) {
request.setAttribute("errorNoReason",
"Please enter a reason");
requestDispatcher.forward(request, response);
return;
}
} else if (choosenType.equals(LeaveType.UNPAID.toString())) {
leave.setLeavetype(LeaveType.UNPAID);
leave.setReason(request.getParameter("reason"));
if (leave.getReason() != null) {
} else if (leave.getReason() == null) {
request.setAttribute("errorNoReason",
"Please enter a reason");
requestDispatcher.forward(request, response);
return;
}
}
// PASSING PARAMETERS TO LOCAL
// VARIABLES---------------------------------------------------------------------------
String prepdate = dateFormat.format(date);
String startdate = request.getParameter("startdate");
String enddate = request.getParameter("enddate");
String oldStartdate = request.getParameter("oldStartdate");
String oldEnddate = request.getParameter("oldEnddate");
person.setName(request.getParameter("name"));
person.setSurname(request.getParameter("surname"));
person.setSskno(request.getParameter("sskno"));
person.setworkStartdate(request.getParameter("workStarted")); // DBden
person.setAddress(request.getParameter("address"));
person.setTelno(request.getParameter("telephone"));
leave.setCalendarday(request.getParameter("calendarday"));
leave.setWorkday(request.getParameter("workday"));
leave.setPrepdate(dateFormat.parse(prepdate));
leave.setStartdate(dateFormat.parse(startdate));
leave.setEnddate(dateFormat.parse(enddate));
leave.setOldStartdate(dateFormat.parse(oldStartdate));
leave.setOldEnddate(dateFormat.parse(oldEnddate));
// Checking the consistency of the
// time----------------------------------------------------------------------------
if (((leave.getEnddate() != null) && (leave.getOldEnddate() != null))) {
entityManager.getTransaction().begin();
entityManager.persist(leave);
entityManager.getTransaction().commit();
//db den return
//info
}
else {
if (leave.getEnddate() == null) {
request.setAttribute("errorMessage1", "Please enter dates correctly");
}
if (leave.getOldEnddate() == null) {
request.setAttribute("errorMessage2", "Please enter date correctly");
}
requestDispatcher.forward(request, response);
}
} catch (Throwable exc) {
System.out.println(exc);
}
finally {
// Close the database connection:
if (entityManager.getTransaction().isActive())
entityManager.getTransaction().rollback();
entityManager.close();
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
And errors...
[EL Info]: 2013-07-29 10:05:47.872--ServerSession(76232710)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-07-29 10:05:48.207--ServerSession(76232710)--file:/C:/Users/VAIO/Desktop/workspace - Kopya/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/EmployeeLeaveForm/WEB-INF/classes/_EmployeeLeaveForm login successful
[EL Warning]: 2013-07-29 10:05:48.292--UnitOfWork(1213364484)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO `Leave` (id, calendarday, enddate, leavetype, oldenddate, oldstartdate, prepdate, reason, startdate, workday, person_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(com.eteration.leavesystem.model.Leave#4fff5f4f)
javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO `Leave` (id, calendarday, enddate, leavetype, oldenddate, oldstartdate, prepdate, reason, startdate, workday, person_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(com.eteration.leavesystem.model.Leave#4fff5f4f)
I also use mysql and i created a database table.
WHY am I getting these exceptions.. And seriously i did digging but nothing work for me pls help me thanks...
EDIT-
[EL Info]: 2013-07-29 11:05:56.944--ServerSession(624062858)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-07-29 11:05:57.283--ServerSession(624062858)--file:/C:/Users/VAIO/Desktop/workspace - Kopya/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/EmployeeLeaveForm/WEB-INF/classes/_EmployeeLeaveForm login successful
[EL Warning]: 2013-07-29 11:05:57.362--ClientSession(72318077)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eteration.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eteration.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")

It seems you try to persist your entity and its id remains null. That's why your get a constraint violation error.
To simply solve this error I suggest you to try create your database table using auto-incrementation option on your id. It should solve your problem, I guess.

It means supply data(from some source and of a type that matches the db field type for "id") for the "id" column to insert into the database with the call. Somewhere you are not supplying and "id" data to the query in your code.

Add
#GeneratedValue(strategy = GenerationType.AUTO)
to your Leave ID
#Id
#Column(name="id",nullable=false,updatable=false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
or create Leave constructor with Long Id arg to set your id. So, you wont be able to create Leave instance with id set to null.

Is it missing GeneratedValue annotation in id field?
If you use AUTO generation, the id generation will be depend on Persistence Provider.
You might need to set auto increment for primary key.
#Entity
#Table(name="Leave")
public class Leave implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id",nullable=false,updatable=false)
private Long id;
#OneToOne
#GeneratedValue(strategy = GenerationType.AUTO) --> remove this code
#JoinColumn(name = "person_id", referencedColumnName="id")
private Person person;
}

You are not setting the id in your code and you are not telling your JPA provider to generate it either.
You can use the #GeneratedValue annotation to tell your JPA provider to generate your id.
Here is an example

I figure it out my problem thank you guys for help. I solved my problem in that way... eclipselink needs sequence table on my database and i created one then it works... Thank you again :)

Related

Spring Data JPA save() return entity

I am using spring boot data jpa as below
#Entity
#Table(name = "invoice")
#Getter
#Setter
#ToString
public class Invoice {
#Id
#Column(name = "inv_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger invId;
#Column(name = "external_id")
private String externalInvoiceId;
#Column(name = "amount")
private double amount;
#JsonIgnore
#JsonIgnoreProperties
#Column(name = "status")
private int status;
#JsonProperty("status")
#Transient
private String invoiceStatus;
public String getInvoiceStatus() {
switch (this.status){
case 1:
return "INITIATED";
case 2:
return "CANCELLED";
case 3:
return "SUCCESS";
case 4:
return "FAILURE";
default:
return "IN PROGRESS";
}
}
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_at")
private Date createdAt;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_at")
private Date updatedAt;
#PostPersist
public void updateExternalID() {
this.externalInvoiceId="G".concat(String.valueOf(this.invId.multiply(BigInteger.valueOf(1000))))
.concat(String.valueOf(Instant.now().getEpochSecond()));
}
}
Am accesing this entiry via repository as below
public interface InvoicesRepository extends JpaRepository<Invoice, BigInteger> {
}
At my #Service am performing the below operation
#Autowired
private InvoicesRepository myInvoicesRepository;
Invoice transactionInvoice = new Invoice();
transactionInvoice.setAmount(200.0);
transactionInvoice.setStatus(1);
Invoice savedInvoice = myInvoicesRepository.save(transactionInvoice);
Am using savedInvoice and trying to update the status. Either it is not updating the status properly nor I could not find the record in database too.
There are no rollback present
Below are the logs I could see insert statements are present
[XNIO-1 task-1] DEBUG org.hibernate.SQL.logStatement -
/* insert com.min.app.model.Invoice
*/ insert
into
invoice
(amount, created_at, external_inv_id, status, updated_at)
values
(?, ?, ?, ?, ?)
Hibernate:
/* insert com.min.app.model.Invoice
*/ insert
into
invoice
(amount, created_at, external_inv_id, status, updated_at)
values
(?, ?, ?, ?, ?)
After the status updates I tried printing the savedInvoice could see the below in logs
Invoice(invId=58, externalInvoiceId=G580001575271905, amount=185.0 status=4, invoiceStatus=FAILURE, createdAt=Mon Dec 02 13:01:45 IST 2019, updatedAt=Mon Dec 02 13:01:45 IST 2019)
The above record I could not see in the table.
What am I doing wrong?
you need to perform transactions in a function call as follows and put your #Autowired repository in Global level ass follows.
class whatever{
#Autowired
private InvoicesRepository myInvoicesRepository;
//call this function
void doSomething(){
Invoice transactionInvoice = new Invoice();
transactionInvoice.setAmount(200.0);
transactionInvoice.setStatus(1);
Invoice savedInvoice = myInvoicesRepository.save(transactionInvoice);
}
}

Insert row using jdbctemplate with PrimaryKey generated by #GeneratedValue

I am inserting a row into an Oracle table in a Spring Boot application. The Primary Key needs to be generated using annotations. I have an entity model that represents the table:
#Entity
#Table(name="PURCH_TENDR")
public class LhlPurchTendrModel implements Serializable {
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
#Column(name="PURCH_TENDR_ID")
private String purchTendrId;
#Column(name="CREATED_BY_NM")
private String createdByNm;
#Column(name="CREATED_DT")
private Timestamp createdDt;
#Column(name="UPDATED_BY_NM")
private String updatedByNm;
#Column(name="UPDATED_DT")
private Timestamp updatedDt;
#Column(name="MODIFY_BY_NM")
private String modifyByNm;
#Column(name="MODIFY_DT")
private Timestamp modifyDt;
#Column(name="CARRIER_TENDER_ID")
private long CarrierTenderId;
#Column(name="EVENT_GMT_TM")
private Timestamp EventGmtTm;
#Column(name="PURCH_COST_ID")
private int PurchCostId;
#Column(name="LAT")
private float Lat;
#Column(name="LON")
private float Lon;
#Column(name="CITY_NM")
private String cityNm;
#Column(name="STATE_CD")
private String stateCd;
#Column(name="CARER_EDI_NBR")
private String carerEdiNbr;
#Column(name="EVENT_STAT_CD")
private String eventStatCd;
#Column(name="ETN_TM")
private Timestamp EtnTm;
#Column(name="PCKUP_NBR")
private String PickupNbr;
#Column(name="VIN")
private String Vin;
#Column(name="EQUIP_NBR")
private String EquipNbr;
#Column(name="EQUIP_PREFIX")
private String EquipPrefix;
There are also getters and setters for these member variables.
I use a Repository class to implements a jdbctemplate to insert the row.
When I use this variation of the insert, I get the error that the column type is invalid:
public boolean insertPurchaseInfo(LhlPurchTendrModel lhlPurchTendrModel) throws SQLException {
boolean success= false;
String ds = lhlJdbcTemplate.getDataSource().getConnection().getSchema();
LOGGER.info("Schema and Insert Purchase Info {}", ds);
String insertSequenceNbrSQLStatement = "INSERT INTO purch_tendr(created_by_nm, created_dt, modify_by_nm, modify_dt, carrier_tender_id, purch_cost_id, event_stat_cd, equip_nbr, equip_prefix) " +
"VALUES (?, SYSDATE, ?, SYSDATE, ?, ?, ?, ?, ?)";
try{
int rowsInserted = lhlJdbcTemplate.update(
insertSequenceNbrSQLStatement,
new Object[] {lhlPurchTendrModel});
if(rowsInserted > 0){
success = true;
}
}
When I try to insert using this code, I get the error 'cannot insert NULL into table Purch_Tendr column Purch_Tendr_Id.
public boolean insertPurchaseInfo(LhlPurchTendrModel lhlPurchTendrModel) throws SQLException {
boolean success= false;
String ds = lhlJdbcTemplate.getDataSource().getConnection().getSchema();
LOGGER.info("Schema and Insert Purchase Info {}", ds);
String insertSequenceNbrSQLStatement = "INSERT INTO purch_tendr(created_by_nm, created_dt, modify_by_nm, modify_dt, carrier_tender_id, purch_cost_id, event_stat_cd, equip_nbr, equip_prefix) " +
"VALUES (?, SYSDATE, ?, SYSDATE, ?, ?, ?, ?, ?)";
try{
int rowsInserted = lhlJdbcTemplate.update(
insertSequenceNbrSQLStatement,
new Object[]{lhlPurchTendrModel.getCreatedByNm(), lhlPurchTendrModel.getModifyByNm(), lhlPurchTendrModel.getCarrierTenderId(), lhlPurchTendrModel.getPurchCostId(),
lhlPurchTendrModel.getEventGmtTm(), lhlPurchTendrModel.getEquipNbr(), lhlPurchTendrModel.getEquipPrefix()});
if(rowsInserted > 0){
success = true;
}
}
I am not sure how to use the #Entity class with JdbcTemplate. How do I indicate to JdbcTemplate to generate the primary key value?
You can't because #Entity and all annotations you use such as #GeneratedValue, #GenericGenerator etc come from JPA while JdbcTemplate behind scene is based on JDBC only which does not know anything about JPA.
If you want to use JPA to manage your data , what you need to look is to choose a JPA implementation (e.g Hibernate is a popular one) and study how to use it through JPA interface but not looking at JdbcTemplate.
Once you get the basic ideas to manage data using JPA , you may consider to look at spring data which is a more high level tool build on top of pure JPA that can help to implement repository / DAO kind of stuff for managing and querying the data.

Hibernate does not save Object even not getting any error in log

I have a single table in db . Created a pojo class to map class instance to table. my class structure is
#Entity
#Table(name = "example")
class example {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
int id;
#Column(name = "SLOT_ID")
int slot_id;
#Column(name = "SLOT_DATE")
String slot_date;
#Column(name = "HOTEL_ID")
String hotel_id;
#Column(name = "ROOM_TYPE_ID")
String room_type_id;
#Column(name = "CREATE_DATE")
String create_date;
#Column(name = "UPDATE_DATE")
String update_date;
#Column(name = "SLOT_PRICE")
Double slot_price;
#Column(name = "AVAILABLE_ROOMS")
Integer available_roooms;
//rest have getter and setter method }
Hibernet commit part
public void save(Example example) {
Session session = null;
try {
log.info( example.toString());
session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(example);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
in log i am getting this log
Hibernate: insert into example(AVAILABLE_ROOMS, CREATE_DATE, HOTEL_ID, ROOM_TYPE_ID, SLOT_DATE, SLOT_ID, SLOT_PRICE, UPDATE_DATE) values (?, ?, ?, ?, ?, ?, ?, ?)
I am able to fetch data from same table here is Code snap `
session = this.sessionFactory.openSession();
Criteria cr = session.createCriteria(Example.class); cr.add(Restrictions.eq("id", id)); List results = cr.list();
if(results.size()>0)
return mapper.writeValueAsString(results.get(0)); //id is auto //incremented in table`
I dont see any error in log but when i cheked in DB no data has been inserted.Any clue what i missed ?
Use this code and test once
public void save(Example example) {
Session session = null;
Transaction tx=null;
try {
log.info( example.toString());
session = this.sessionFactory.openSession();
tx = session.beginTransaction();
session.persist(example);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (!tx.wasCommitted()) {
tx.rollback();
}//not much doing but a good practice
session.flush(); //this is where I think things will start working.
session.close();
}
}
Good reason to call flush before close is here
i think you have to use session.save() instead of session.persist(), or you have to use flush at the end of transaction as pointed by Viraj, also refer this post
What's the advantage of persist() vs save() in Hibernate?

error while trying to add new value for JPA table

Im using JPa API's and its work well ,I have tried to add new member/column to the class(table) and when I was tried to add data for it works fine but in the commit part I get dump with the following error
Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'DOUBLE1' is not a column in table or VTI 'TEST.PERSON'.
Error Code: 20000
Call: INSERT INTO PERSON (ID, DOUBLE1, FIRSTNAME, LASTNAME, NONSENSEFIELD) VALUES (?, ?, ?, ?, ?)
bind => [5 parameters bound]
But in the table person I have added the member double1 as follows
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private String id;
private String firstName;
private String lastName;
private double double1;
....
public double getDouble1() {
return double1;
}
public void setDouble1(double double1) {
this.double1 = double1;
}
What am i missing here?
There is obviously no column DOUBLE1 in the database table VTI 'TEST.PERSON'. Adding a new field to a JPA entity does not automatically make it appear in the database as well.

JPA/MySql issue

I am building JPA based application using mysql and ecliselink.I have very strange issue when try to insert stuff into my database.I am able to insert data into single table but when it comes to one-to-may and vice versa something goes wrong.Currently I have 2 main and 1 reference table(it holds the foreign keys of the other two tables).It is strange because I dont have "sequence" in my database table When I try to insert data into any of my tables I get this exception:
[EL Info]: 2012-03-15 17:52:28.64--ServerSession(18621340)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
[EL Info]: 2012-03-15 17:52:29.23--ServerSession(18621340)--file:/D:/git-eclipse/Martin/reference/build/classes/_reference login successful
[EL Warning]: 2012-03-15 17:52:29.389--ClientSession(31843177)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eclipse1.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eclipse1.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
[EL Info]: 2012-03-15 17:52:29.394--ServerSession(18621340)--file:/D:/git-eclipse/Martin/reference/build/classes/_reference logout successful
Exception in thread "main" java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManager.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.verifyOpen(EntityManagerImpl.java:1665)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.close(EntityManagerImpl.java:1529)
at OneToManyRelation.main(OneToManyRelation.java:47)
I am posting one class only because others are quite similar
#Entity
#Table(name="category")
public class Category {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="CategoryID")
private int CategoryID;
/**
* #return the id
*/
public int getId() {
return CategoryID;
}
/**
* #param id the id to set
*/
public void setId(int CategoryID) {
this.CategoryID = CategoryID;
}
#Column(name="category", nullable=false, length=50, insertable=true)
private String category;
/**
* #return the category
*/
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
#OneToMany(cascade=CascadeType.ALL)
#JoinTable(name = "templateemail", joinColumns = {
#JoinColumn(name="categoryId", unique = true)
},
inverseJoinColumns = {
#JoinColumn(name="templateId")
}
)
private Set<Template> template;
/**
*
*/
public Set<Template> getChildren() {
return template;
}
/**
*
*/
public void setChildren(Set<Template> template) {
this.template = template;
}
}
Do you have any idea what is wrong with my code?
Thanks in advance
Seeing the code would help finding what's wrong with it. But by judging on the error message only, it seems you chose to use a sequence or table generator, and that this generator relies (by default) on a table named sequence, that doesn't exist in the database.
Create this table, or configure the generator to use an existing table, or change the ID generator.

Categories

Resources