Error Joining Tables in hibernate - java

Hello I am trying to join the User And Candidate table. I want column firstname, lastname, email, phone from Candidate table and join with password column of User table. I tried doing this but getting some sort of error. My code is given below:
CREATE TABLE `candidate` (`candidate_id` bigint(12) NOT NULL,`user_id` int(11) DEFAULT NULL,`firstname` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,`lastname` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,`dob` date DEFAULT NULL,`gender` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,`phone` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`address_id` int(11) DEFAULT NULL,`profile_title` varchar(120) COLLATE utf8_unicode_ci DEFAULT NULL,`profile_summary` varchar(10000) COLLATE utf8_unicode_ci DEFAULT NULL,`total_experience` int(11) DEFAULT NULL COMMENT 'year,month',`current_location` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`current_salary` double DEFAULT NULL,`expected_salary` double DEFAULT NULL,`status` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`percentage` int(45) DEFAULT NULL,`updated_on` timestamp NULL DEFAULT CURRENT_TIMESTAMP,`noticeperiod` int(11) DEFAULT NULL,`martialstatus` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`currentoffer` double DEFAULT NULL,`idproof` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`industry` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,`functionalarea` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,`functionalrole` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,`resign` bit(1) DEFAULT NULL,`preferlocation` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL,`type` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,`notice_period_update` timestamp NULL DEFAULT NULL,`passport` bit(1) DEFAULT NULL,`gross_salary` double DEFAULT NULL,`profile_type` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL,`rrm_user_id` int(11) DEFAULT NULL, PRIMARY KEY (`candidate_id`), KEY `Candidate_Address_idx` (`address_id`),KEY `Can_user` (`user_id`),KEY `CandidateStatus_idx` (`status`),KEY `CandidatePercent_idx` (`percentage`), KEY `user_id_idx` (`rrm_user_id`),CONSTRAINT `Can_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT `Candidate_Address` FOREIGN KEY (`address_id`) REFERENCES `address`(`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `user_id` FOREIGN KEY (`rrm_user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
My User Table:
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,`password` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,`first_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,`last_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,`type` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,`active` bit(1) DEFAULT NULL,`deleted` bit(1) DEFAULT NULL,`timezone` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,`created_on` timestamp NULL DEFAULT NULL,`updated_on` timestamp NULL DEFAULT CURRENT_TIMESTAMP,`activationcode` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,`secure_key` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `username_UNIQUE` (`username`)) ENGINE=InnoDB AUTO_INCREMENT=1505 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
My Entity Class:
#Table(name = "CANDIDATE")public class SignUp {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String candidate_id;
#Column
private String firstname;
#Column
private String lastname;
#Column
private String email;
#Column
private String phone;
public String getCandidate_id() {
return candidate_id;
}
public void setCandidate_id(String candidate_id) {
this.candidate_id = candidate_id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "candidate_id")
private Password password;
public Password getPassword() {
return password;
}
public void setPassword(Password password) {
this.password = password;
}
For User Table:
#Table(name = "USER")public class Password { #Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
#Column
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
private SignUp signUp;
public SignUp getSignUp() {
return signUp;
}
public void setSignUp(SignUp signUp) {
this.signUp = signUp;
}
Error m getting is:
Hibernate:
select
password0_.id as id1_1_0_,
password0_.password as password2_1_0_,
password0_.user_id as user_id4_1_0_,
signup1_.candidate_id as candidat1_0_1_,
signup1_.email as email2_0_1_,
signup1_.firstname as firstnam3_0_1_,
signup1_.lastname as lastname4_0_1_,
signup1_.phone as phone5_0_1_
from
User password0_
left outer join
CANDIDATE signup1_
on password0_.user_id=signup1_.candidate_id
where
password0_.id=?
Jun 01, 2017 4:48:45 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN:
SQL Error: 1054, SQLState: 42S22 Jun 01, 2017 4:48:45 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR:
Unknown column 'password0_.user_id' in 'field list'

Your mappings are fine, you just missed the user_id in the CREATE TABLE user statement as based on this mapping:
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
private SignUp signUp;
hibernate expects to make a join to the CERTIFICATE table through that column.
Also dont forget to add the foreign key statement in your DDL.

Try to use Jboss reverse engineering tool for hibernate to generate domain and avoid such mistakes.It is very easy and you can create domains from database table within 5 minutes.

Related

JPA Entity Creation

I have been trying to create JPA entity using schema of Mysql Sample Database , JPA tools of Eclipse JPA entites are generated using i am having for establishing entity relationship for below scenarios and tables
Employee Table : Employee tables has field reportsto which refers back to employee i.e one employee reports to another employee
Office Table: One office can have more then one Employee
Below are JPA Entities :
#Entity
#Table(name="employees")
#NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String email;
private String extension;
private String firstName;
private String jobTitle;
private String lastName;
//bi-directional one-to-one association to Customer
#OneToOne(mappedBy="employee")
private Customer customer;
//bi-directional many-to-one association to Office
#ManyToOne
#JoinColumn(name="officeCode", referencedColumnName="officeCode")
private Office office;
//bi-directional many-to-one association to Employee
#ManyToOne
#JoinColumn(name="reportsTo", referencedColumnName="employeeNumber")
private Employee employee;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="employee")
private List<Employee> employees;
}
Table Description
CREATE TABLE `employees` (
`employeeNumber` int(11) NOT NULL,
`lastName` varchar(50) NOT NULL,
`firstName` varchar(50) NOT NULL,
`extension` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`officeCode` varchar(10) NOT NULL,
`reportsTo` int(11) DEFAULT NULL,
`jobTitle` varchar(50) NOT NULL,
PRIMARY KEY (`employeeNumber`),
KEY `reportsTo` (`reportsTo`),
KEY `officeCode` (`officeCode`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`reportsTo`) REFERENCES `employees` (`employeeNumber`),
CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)
)
When app loads we get below error message
referencedColumnNames(employeeNumber) of com.train.model.Employee.employee referencing com.train.model.Employee not mapped to a single property
when i add field employeeNumber and generate getters and setters , i get below error
referencedColumnNames(officeCode) of com.train.model.Employee.office referencing com.train.model.Office not mapped to a single property
Office JPA Entity
#Entity
#Table(name="offices")
#NamedQuery(name="Office.findAll", query="SELECT o FROM Office o")
public class Office implements Serializable {
private static final long serialVersionUID = 1L;
private String addressLine1;
private String addressLine2;
private String city;
private String country;
private String phone;
private String postalCode;
private String state;
private String territory;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="office")
private List<Employee> employees;
}
Table Description
CREATE TABLE `offices` (
`officeCode` varchar(10) NOT NULL,
`city` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`postalCode` varchar(15) NOT NULL,
`territory` varchar(10) NOT NULL,
PRIMARY KEY (`officeCode`)
)
Why employee entity complains of not having officeCode and what is right entity for Employee and Office

Why this Hibernate Relation isn't working?

I try to Connect Pizzas and Ingredients in a n:m relation while all Pizzas have Ingredients as an Attribute List of Ingredients. But in the Relationstable when I create a new Pizza and try to commit there is an Error with the PizzaID in the Relationtable.
The relational Table:
CREATE TABLE `Pizza_Ingredience_Relation` (
`PizzaID` int(11) NOT NULL,
`IngredientID` int(11) NOT NULL,
`Amount` int(11) NOT NULL,
`Volume_Unit` varchar(1) NOT NULL,
PRIMARY KEY (`PizzaID`,`IngredientID`),
KEY `FKc58en2gx5a8n1swmu9tda345` (`IngredientID`),
CONSTRAINT `FK_IngredienceId` FOREIGN KEY (`IngredientID`) REFERENCES `Zutatenliste` (`ID`),
CONSTRAINT `FKc58en2gx5a8n1swmu9tda345` FOREIGN KEY (`IngredientID`) REFERENCES `Zutatenliste` (`ID`),
CONSTRAINT `FKhghfxg8raskdydyu8o8msxtfn` FOREIGN KEY (`PizzaID`) REFERENCES `Pizza` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
The Ingredient Table:
CREATE TABLE `Zutatenliste` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
The Pizza Table:
CREATE TABLE `Pizza` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) NOT NULL,
`PreisKlein` double NOT NULL,
`PreisMittel` double NOT NULL,
`PreisGroß` double NOT NULL,
`PreisFamilie` double NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
I have two hibernate Entitites, one is a Pizza Entitiy and one the Ingredient Entitiy:
package Model.PizzenDB.SQLConnectionClasses.MySQL;
import Model.PizzenDB.Pizza;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.util.LinkedList;
import java.util.Set;
#Entity
#Table(name = "Pizza")
public class MySQLPizzaHibernateEntity {
#Id
#Column(name = "ID")
private int id;
#Column(name = "Name")
private String name;
#Column(name = "PreisKlein")
private double smallPrice;
#Column(name = "PreisMittel")
private double middlePrice;
#Column(name = "PreisGroß")
private double bigPrice;
#Column(name = "PreisFamilie")
private double familyPrice;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name = "Pizza_Ingredience_Relation",
joinColumns = { #JoinColumn(name = "PizzaID", referencedColumnName = "ID") },
inverseJoinColumns = { #JoinColumn(name = "IngredientID") }
)
private Set<MySQLIngredientWithAmountHibernateEntity> ingredience;
public MySQLPizzaHibernateEntity(String name, double smallPrice, double middlePrice, double bigPrice, double familyPrice) {
this.name = name;
this.smallPrice = smallPrice;
this.middlePrice = middlePrice;
this.bigPrice = bigPrice;
this.familyPrice = familyPrice;
}
public MySQLPizzaHibernateEntity() {
}
}
#Entity
#Table(name = "Zutatenliste")
#SecondaryTable(name = "Pizza_Ingredience_Relation", pkJoinColumns = #PrimaryKeyJoinColumn(name = "IngredientID", referencedColumnName = "ID"))
public class MySQLIngredientWithAmountHibernateEntity {
#Id
#Column(name = "ID")
private int id;
#Column(name = "Name")
private String name;
#Column(table = "Pizza_Ingredience_Relation", name="Amount")
private int amount;
#Column(table = "Pizza_Ingredience_Relation", name = "Volume_Unit")
private char unit;
public MySQLIngredientWithAmountHibernateEntity(String name) {
this.name = name;
}
public MySQLIngredientWithAmountHibernateEntity() {
this("");
}
}
I get the following error message:
20:41:45 [main] [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] ERROR - Field 'PizzaID' doesn't have a default value
20:41:45 [main] [org.hibernate.internal.ExceptionMapperStandardImpl] ERROR - HHH000346: Error during managed flush [org.hibernate.exception.GenericJDBCException: could not execute statement]
I'm not sure what is wrong in detail I guess it has todo with the PizzaID Foreign Key and that it isn't set properly.
For many to many relationship, you are using middle table with extra columns and you need Embeddable key for that which would comprise of Pizza and Ingredient object (names shortened). Something like:
#Embeddable
public class PizzaIngredientPk {
private MySQLPizzaHibernateEntity pizza;
private MySQLIngredientWithAmountHibernateEntity ingredient;
#ManyToOne
public MySQLPizzaHibernateEntity getPizza() {
return pizza;
}
public void setPizza(MySQLPizzaHibernateEntity pizza) {
this.pizza = pizza;
}
#ManyToOne
public MySQLIngredientWithAmountHibernateEntity getIngredient() {
return ingredient;
}
public void setIngredientID(MySQLIngredientWithAmountHibernateEntity ingredient) {
this.ingredient = ingredient;
}
}
Then this would act as Embedded Key in MySQLIngredientWithAmountHibernateEntity as
#EmbeddedId
PizzaIngredientPk pk = new PizzaIngredientPk();
But this won't work with Secondarytable which is used for one-to-one relationship. #SecondaryTable requires mapping to be with a primary key but in this case Embedded ID would become PK. In fact, you have flaw in your design. You are trying to make one side of your many to many relationship as one-to-one.
As per JPA docs There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.
Try to specify to Hibernate automatically produce primary keys. Put this annotation above your Id fields and re-create your database.
#GeneratedValue(strategy = GenerationType.IDENTITY)
See: https://thoughts-on-java.org/hibernate-tips-use-auto-incremented-column-primary-key/

Error: The abstract schema type is unknown

I don't understand why I get this error:
//EX[2,1,["java.lang.IllegalArgumentException/1755012560",
"An exception occurred while creating a query in EntityManager:
\r\nException Description: Problem compiling [SELECT u FROM Users u]. \n[14, 19]
The abstract schema type \x27Users\x27 is unknown."],0,7]
It looks like all configs are correct, but nevertheless I get this error.
Please, help. My configs are below:
MySql table:
CREATE TABLE `users` (
`USER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`USERNAME` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`PASSWORD` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`ENABLED` tinyint(1) NOT NULL,
`firstname` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`lastname` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
Entity:
package com.val.dogovora.entity;
import javax.persistence.*;
import java.io.Serializable;
#Entity
public class Users implements Serializable {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int USER_ID;
private String USERNAME;
private String PASSWORD;
private int ENABLED;
private String firstname;
private String lastname;
private String email;
public Users() {
}
public Users(String USERNAME, String PASSWORD, int ENABLED, String firstname, String lastname, String email) {
this.USERNAME = USERNAME;
this.PASSWORD = PASSWORD;
this.ENABLED = ENABLED;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
}
Getters and Setters...
}
persistence.xml
<class>com.val.dogovora.entity.Users</class>
code:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DogovoraPool");
EntityManager em = emf.createEntityManager();
TypedQuery<Users> query = em.createQuery("SELECT u FROM Users u", Users.class);
I think I found the reason of my error. Before I converted my project from Eclipse into Intellij Idea. The folder my_project_name/war/web-if/classes remains with old files. I deleted this folder and now my project works without any error. But I don't understand, why does Intellij Idea use these old classes, if it has it's own folder for them my_project_name/out ?

Hibernate Exception while defining mapping

I am working on a project and using Hibernate for database interaction.
I have two tables, one is RESOURCE_PROFILE and second is PROJECT_MASTER. Below are the DDL statements.
CREATE TABLE USER_PROFILE (
FIRST_NAME VARCHAR(15) NOT NULL,
MIDDLE_NAME VARCHAR(15),
LAST_NAME VARCHAR(15) NOT NULL,
EMAIL_ID VARCHAR(40) NOT NULL,
USER_ID VARCHAR(40) NOT NULL,
PASSWORD VARCHAR(1000) NOT NULL,
ROLE VARCHAR(20),
SUPERVISOR_ID VARCHAR(20),
SUBMITTED_BY VARCHAR(20),
SUBMITTED_DATE DATE,
PRIMARY KEY (USER_ID)
);
CREATE TABLE PROJECT_MASTER (
PROJECT_ID INT NOT NULL AUTO_INCREMENT,
PROJECT_NAME VARCHAR(50) NOT NULL,
PROJECT_NUMBER VARCHAR(50) NOT NULL,
START_DATE DATE,
END_DATE DATE,
PROJECT_MANAGER_ID VARCHAR(40) NOT NULL,
PROJECT_SUPERVISOR_ID VARCHAR(40) NOT NULL,
SUBMITTED_BY VARCHAR(40),
SUBMITTED_DATE DATE,
UPDATED_BY VARCHAR(40),
PRIMARY KEY (PROJECT_ID),
FOREIGN KEY (PROJECT_MANAGER_ID) REFERENCES USER_PROFILE(USER_ID),
FOREIGN KEY (PROJECT_SUPERVISOR_ID) REFERENCES USER_PROFILE(USER_ID),
FOREIGN KEY (SUBMITTED_BY) REFERENCES USER_PROFILE(USER_ID),
FOREIGN KEY (UPDATED_BY) REFERENCES USER_PROFILE(USER_ID)
);
As you can see in the PROJECT_MASTER table I am using the USER_ID(RESOURCE_PROFILE) as a foreign key for multiple columns in PROJECT_MASTER table. Below is the entity class I created for these two tables. I am sure that I am doing something wrong in the mapping, can you please help me and point me to the right direction?
Since I have the same foreign key getting used for multiple columns, how can I achieve this mapping?
#Entity
#Table(name = "PROJECT_MASTER")
public class ProjectMasterBean {
#Id
#GeneratedValue
#Column(name="PROJECT_ID")
private int projectID;
#Column(name="PROJECT_NAME")
private String projectName;
#Column(name="PROJECT_NUMBER")
private String projectNumber;
#Column(name="START_DATE")
private Date startDate;
#Column(name="END_DATE")
private Date endDate;
#ManyToOne
#JoinColumn(name="USER_ID",insertable=false, updatable=false,
nullable=false)
private UserProfileBean projectManagerID;
#ManyToOne
#JoinColumn(name="USER_ID",insertable=false, updatable=false,
nullable=false)
private UserProfileBean projectSupervisorID;
#ManyToOne
#JoinColumn(name="USER_ID",insertable=false, updatable=false,
nullable=false)
private UserProfileBean submittedBy;
}
#Column(name="SUBMITTED_DATE")
private Date submittedDate;
#ManyToOne
#JoinColumn(name="USER_ID",insertable=false, updatable=false,
nullable=false)
private UserProfileBean updatedBy;
public class UserProfileBean {
#Id
#Column(name="USER_ID")
private String userID;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="MIDDLE_NAME")
private String middleName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="EMAIL_ID")
private String emailID;
#Column(name="PASSWORD")
private String password;
#Column(name="ROLE")
private String userRole;
#Column(name="SUPERVISOR_ID")
private String supervisorID;
#Column(name="SUBMITTED_BY")
private String submittedBy;
#Column(name="SUBMITTED_DATE")
private String submittedDate;
}
This is the exception I am getting:
Hibernate: insert into PROJECT_MASTER (PROJECT_NAME, PROJECT_NUMBER, START_DATE, END_DATE, SUBMITTED_BY, SUBMITTED_DATE, UPDATED_BY) values (?, ?, ?, ?, ?, ?, ?)
Sep 12, 2013 8:46:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet action threw exception
java.sql.SQLException: Field 'PROJECT_MANAGER_ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
Insert Query doesn't even have those two columns. This is how the query should be.
Hibernate: insert into PROJECT_MASTER (PROJECT_NAME, PROJECT_NUMBER, START_DATE, END_DATE, PROJECT_MANAGET_ID , PROJECT_SUPERVISOR_ID , SUBMITTED_BY, SUBMITTED_DATE, UPDATED_BY) values (?, ?, ?, ?, ?, ?, ?,?,?)
You've created your table with
CREATE TABLE PROJECT_MASTER ( PROJECT_ID INT NOT NULL AUTO_INCREMENT,
PROJECT_NAME VARCHAR(50) NOT NULL, PROJECT_NUMBER VARCHAR(50) NOT
NULL, START_DATE DATE, END_DATE DATE, PROJECT_MANAGER_ID VARCHAR(40)
NOT NULL, PROJECT_SUPERVISOR_ID VARCHAR(40) NOT NULL, SUBMITTED_BY
VARCHAR(40), SUBMITTED_DATE DATE, UPDATED_BY VARCHAR(40), PRIMARY KEY
(PROJECT_ID), FOREIGN KEY (PROJECT_MANAGER_ID) REFERENCES
USER_PROFILE(USER_ID), FOREIGN KEY (PROJECT_SUPERVISOR_ID) REFERENCES
USER_PROFILE(USER_ID), FOREIGN KEY (SUBMITTED_BY) REFERENCES
USER_PROFILE(USER_ID), FOREIGN KEY (UPDATED_BY) REFERENCES
USER_PROFILE(USER_ID) );
And you've made your class uses this Table. Because you don't have a default value for a NOT NULL field, Hibernate complains. Either delete that column from the table or add a relationship in your entity mapping.
Change to
#ManyToOne
#JoinColumn(name="PROJECT_MANAGER_ID ",insertable=false, updatable=false,
nullable=false)
private UserProfileBean projectManagerID;

OpenJPA Mysql always getting id null

I'm trying to run a simple example which is just a mapping with a table and to print all the values stored in it.
I'm getting all my fields well except my id.
Here is my table when i do an export on it
CREATE TABLE `adress` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`streetNumber` tinyint(4) DEFAULT NULL,
`street` varchar(45) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
`zipCode` int(11) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
LOCK TABLES `adress` WRITE;
INSERT INTO `adress` VALUES (1,12,'Canada street','LOS ANGELES',441233,'California'),(2,54,'5th avenue','NEW YORK CITY',884769,'New York');
UNLOCK TABLES;
My Entity class :
#Entity
#Table(name = "adress")
#XmlRootElement
public class Adress implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "streetNumber")
private Short streetNumber;
...
If i do a "findAll()" i'm able to get all my datas from the db.
But the id is null, all the other fields have their values
I have tried several stuff but i'm not going everywhere.
If someone can see where or about what is my mistake i'll appreciate a lot your help.
Thanks in advance

Categories

Resources