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;
Related
I'm new to JPA and trying to understand if there's a way to make an Entity where one column is coming from another table that is linked by a foreign key. For example, consider the following tables:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `jobs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11),
PRIMARY KEY (`id`),
CONSTRAINT `fk_jobs_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
);
Now I want to make an Entity for the "jobs" table that will include the user.email. I know I can do something like
#Entity
#Table(name = "jobs")
public class JobEntity {
#Id
#Column(name = "id")
private Long id;
#Column(name = "user_id")
private Long userId;
#Formula("(select user.email FROM user WHERE user.id = user_id)")
private String userEmail;
But I feel there's a way I can better leverage the foreign key relationship, but I'm not sure how. I was looking into #JoinColumn but was not seeing the result I wanted since the foreign key is a different column in my Entity. Is there a better way rather than using #Forula to do this?
I don't really understand this. I'm sure #JoinColumn can accomplish the behavior you're looking for.
I was looking into #JoinColumn but was not seeing the result I wanted since the foreign key is a different column in my Entity
Example:
#Entity
#Table(name = "jobs")
public class KronosFileEntity {
#Id
#Column(name = "id")
private Long id;
#ManyToOne
#JoinColumn(name = "user_id", referencedColumn = "id")
private User user;
}
Then you can access the email like job.getUser().getEmail()
Or add a convenience method if that helps
public String getUserEmail() {
return user.getEmail();
}
Then
job.getUserEmail()
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
How to create custom query in spring for getting all user who follow me from database..this is my repository
#Repository
public interface FollowRepository extends JpaRepository<Follow, Long> {
#Query("Select f from Follow f where f.user = :user and f.status = 'follow'")
List<Follow> findByUser (#Param("user") User user);
}
and this is my table in database
CREATE TABLE IF NOT EXISTS `follow`(
`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`user_id` BIGINT,
`follower_id` BIGINT,
`status` ENUM ('follow','blocked') NOT NULL,
FOREIGN KEY (user_id) REFERENCES `user`(id),
FOREIGN KEY (follower_id) REFERENCES `user`(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#Query("Select f from Follow f where f.userId = ?1 and f.status = ?2")
List<Follow> findByUser (Integer userId, String status);
You could also:
List<Follow> findByUserAndStatus(User user, String status);
EDIT: Having your status as an ENUM in your table can make it stressful when making new enums. I'd prefer having the status column as a VARCHAR and in your entity your getter for that field can be:
#Basic
#Column(name = "status")
#Enumerated(EnumType.STRING)
public StatusEnum getStatus(){ return this.getStatus; }
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.
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 ?