Hibernate: "Field 'id' doesn't have a default value" - java

I'm facing what I think is a simple problem with Hibernate, but can't solve it (Hibernate forums being unreachable certainly doesn't help).
I have a simple class I'd like to persist, but keep getting:
SEVERE: Field 'id' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert: [hibtest.model.Mensagem]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
[ a bunch more ]
Caused by: java.sql.SQLException: Field 'id' doesn't have a default value
[ a bunch more ]
The relevant code for the persisted class is:
package hibtest.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Mensagem {
protected Long id;
protected Mensagem() { }
#Id
#GeneratedValue
public Long getId() {
return id;
}
public Mensagem setId(Long id) {
this.id = id;
return this;
}
}
And the actual running code is just plain:
SessionFactory factory = new AnnotationConfiguration()
.configure()
.buildSessionFactory();
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Mensagem msg = new Mensagem("YARR!");
session.save(msg);
tx.commit();
session.close();
}
I tried some "strategies" within the GeneratedValue annotation but it just doesn't seem to work. Initializing id doesn't help either! (eg Long id = 20L).
Could anyone shed some light?
EDIT 2: confirmed: messing with#GeneratedValue(strategy = GenerationType.XXX) doesn't solve it
SOLVED: recreating the database solved the problem

Sometimes changes made to the model or to the ORM may not reflect accurately on the database even after an execution of SchemaUpdate.
If the error actually seems to lack a sensible explanation, try recreating the database (or at least creating a new one) and scaffolding it with SchemaExport.

If you want MySQL to automatically produce primary keys then you have to tell it when creating the table. You don't have to do this in Oracle.
On the Primary Key you have to include AUTO_INCREMENT. See the example below.
CREATE TABLE `supplier`
(
`ID` int(11) NOT NULL **AUTO_INCREMENT**,
`FIRSTNAME` varchar(60) NOT NULL,
`SECONDNAME` varchar(100) NOT NULL,
`PROPERTYNUM` varchar(50) DEFAULT NULL,
`STREETNAME` varchar(50) DEFAULT NULL,
`CITY` varchar(50) DEFAULT NULL,
`COUNTY` varchar(50) DEFAULT NULL,
`COUNTRY` varchar(50) DEFAULT NULL,
`POSTCODE` varchar(50) DEFAULT NULL,
`HomePHONENUM` bigint(20) DEFAULT NULL,
`WorkPHONENUM` bigint(20) DEFAULT NULL,
`MobilePHONENUM` bigint(20) DEFAULT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here's the Entity
package com.keyes.jpa;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigInteger;
/**
* The persistent class for the parkingsupplier database table.
*
*/
#Entity
#Table(name = "supplier")
public class supplier implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
**#GeneratedValue(strategy = GenerationType.IDENTITY)**
#Column(name = "ID")
private long id;
#Column(name = "CITY")
private String city;
#Column(name = "COUNTRY")
private String country;
#Column(name = "COUNTY")
private String county;
#Column(name = "EMAIL")
private String email;
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "HomePHONENUM")
private BigInteger homePHONENUM;
#Column(name = "MobilePHONENUM")
private BigInteger mobilePHONENUM;
#Column(name = "POSTCODE")
private String postcode;
#Column(name = "PROPERTYNUM")
private String propertynum;
#Column(name = "SECONDNAME")
private String secondname;
#Column(name = "STREETNAME")
private String streetname;
#Column(name = "WorkPHONENUM")
private BigInteger workPHONENUM;
public supplier()
{
}
public long getId()
{
return this.id;
}
public void setId(long id)
{
this.id = id;
}
public String getCity()
{
return this.city;
}
public void setCity(String city)
{
this.city = city;
}
public String getCountry()
{
return this.country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getCounty()
{
return this.county;
}
public void setCounty(String county)
{
this.county = county;
}
public String getEmail()
{
return this.email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getFirstname()
{
return this.firstname;
}
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
public BigInteger getHomePHONENUM()
{
return this.homePHONENUM;
}
public void setHomePHONENUM(BigInteger homePHONENUM)
{
this.homePHONENUM = homePHONENUM;
}
public BigInteger getMobilePHONENUM()
{
return this.mobilePHONENUM;
}
public void setMobilePHONENUM(BigInteger mobilePHONENUM)
{
this.mobilePHONENUM = mobilePHONENUM;
}
public String getPostcode()
{
return this.postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public String getPropertynum()
{
return this.propertynum;
}
public void setPropertynum(String propertynum)
{
this.propertynum = propertynum;
}
public String getSecondname()
{
return this.secondname;
}
public void setSecondname(String secondname)
{
this.secondname = secondname;
}
public String getStreetname()
{
return this.streetname;
}
public void setStreetname(String streetname)
{
this.streetname = streetname;
}
public BigInteger getWorkPHONENUM()
{
return this.workPHONENUM;
}
public void setWorkPHONENUM(BigInteger workPHONENUM)
{
this.workPHONENUM = workPHONENUM;
}
}

Take a look at GeneratedValue's strategy. It typically looks something like:
#GeneratedValue(strategy=GenerationType.IDENTITY)

you must be using update in your hbm2ddl property. make the changes and update it to Create so that it can create the table.
<property name="hbm2ddl.auto">create</property>
It worked for me.

Dropping the table from the database manually and then re-running the application worked for me. In my case table was not created properly(with constraints) I guess.

I had this issue. My mistake was i had set the insertable and updatable fileds as false and was trying to set the field in the request. This field is set as NON NULL in DB.
#ManyToOne
#JoinColumn(name="roles_id", referencedColumnName = "id", insertable = false, updatable = false, nullable=false)
#JsonBackReference
private Role role;
Later I changed it to - insertable = true, updatable = true
#ManyToOne
#JoinColumn(name="roles_id", referencedColumnName = "id", insertable = true, updatable = true, nullable=false)
#JsonBackReference
//#JsonIgnore
private Role role;
It worked perfectly later.

I came here because of the error message, turns out I had two tables with the same name.

I had the same problem. I found the tutorial Hibernate One-To-One Mapping Example using Foreign key Annotation and followed it step by step like below:
Create database table with this script:
create table ADDRESS (
id INT(11) NOT NULL AUTO_INCREMENT,
street VARCHAR(250) NOT NULL,
city VARCHAR(100) NOT NULL,
country VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
create table STUDENT (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
entering_date DATE NOT NULL,
nationality TEXT NOT NULL,
code VARCHAR(30) NOT NULL,
address_id INT(11) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT student_address FOREIGN KEY (address_id) REFERENCES ADDRESS (id)
);
Here is the entities with the above tables
#Entity
#Table(name = "STUDENT")
public class Student implements Serializable {
private static final long serialVersionUID = 6832006422622219737L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
}
#Entity
#Table(name = "ADDRESS")
public class Address {
#Id #GeneratedValue
#Column(name = "ID")
private long id;
}
The problem was resolved.
Notice: The primary key must be set to AUTO_INCREMENT

Another suggestion is to check that you use a valid type for the auto-generated field. Remember that it doesn't work with String, but it works with Long:
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long id;
#Constraints.Required
public String contents;
The above syntax worked for generating tables in MySQL using Hibernate as a JPA 2.0 provider.

Just add not-null constraint
I had the same problem. I just added not-null constraint in xml mapping. It worked
<set name="phone" cascade="all" lazy="false" >
<key column="id" not-null="true" />
<one-to-many class="com.practice.phone"/>
</set>

Maybe that is the problem with the table schema. drop the table and rerun the application.

In addition to what is mentioned above, do not forget while creating sql table to make the AUTO INCREMENT as in this example
CREATE TABLE MY_SQL_TABLE (
USER_ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
FNAME VARCHAR(50) NOT NULL,
LNAME VARCHAR(20) NOT NULL,
EMAIL VARCHAR(50) NOT NULL
);

When your field is not nullable it requires a default value to be specified on table creation. Recreate a table with AUTO_INCREMENT properly initialized so DB will not require default value since it will generate it by itself and never put NULL there.
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
https://www.w3schools.com/sql/sql_autoincrement.asp

I solved it changuing #GeneratedValue(strategy = GenerationType.IDENTITY) by #GeneratedValue(strategy = GenerationType.AUTO)
By the way i didn't need to put it to create, just:
spring.jpa.hibernate.ddl-auto: update

Please check whether the Default value for the column id in particular table.if not make it as default

I had the same problem. I was using a join table and all I had with a row id field and two foreign keys. I don't know the exact caused but I did the following
Upgraded MySQL to community 5.5.13
Rename the class and table
Make sure I had hashcode and equals methods
#Entity
#Table(name = "USERGROUP")
public class UserGroupBean implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "USERGROUP_ID")
private Long usergroup_id;
#Column(name = "USER_ID")
private Long user_id;
#Column(name = "GROUP_ID")
private Long group_id;

The same exception was thrown if a DB table had an old unremoved column.
For example:
attribute_id NOT NULL BIGINT(20), and attributeId NOT NULL BIGINT(20),
After removing the not used attribute, in my case contractId, the problem was resolved.

This happened to me with a #ManyToMany relationship. I had annotated one of the fields in the relationship with #JoinTable, I removed that and used the mappedBy attribute on #ManyToMany instead.

I tried the code and in my case the code below solve the issue. I had not settled the schema properly
#Entity
#Table(name="table"
,catalog="databasename"
)
Please try to add ,catalog="databasename" the same as I did.
,catalog="databasename"

In my case,
I altered that offending tables and the field "id" in question I made it AUTO_INCREMENT, I still need to figure out why on deployment time it was not making it "AUTO_INCREMENT" so that I have to do it by myself!

What about this:
<set name="fieldName" cascade="all">
<key column="id" not-null="true" />
<one-to-many class="com.yourClass"/>
</set>
I hope it helps you.

Try to change Long object type to long primitive type (if using primitives is ok for you).
I had the same problem and changing type helped me.

I had this issue, by mistake I had placed #Transient annotation above that particular attribute. In my case this error make sense.

"Field 'id' doesn't have a default value" because you didn't declare GenerationType.IDENTITY in GeneratedValue Annotation.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

This issue is because sometimes you need to again update/create the database or sometimes if you have added the field in db table but not not entity class then it can not insert any null value or zero so this error came.
So check both side.Db and Entity class.

i have got such error in GCP cloud sql when model field didn't match correct table field in db.
Example:
when in model field is fieldName
table in db should have field field_name
Fixing table field name helped me.

I solved similar problem, when I altered the database column type , and did not add auto_increment. After adding back auto_increment in the alter table command (as in my original table creation) it worked

In my case I have not added the below property in my application.properties file:
spring.jpa.database-platform = org.hibernate.dialect.MySQL5InnoDBDialect
And added the following annotation to my entity class's Id column:
#GeneratedValue(strategy = GenerationType.IDENTITY)
And after adding this I have also drop my table manually from datatbase and run my project again that creates a new table with all default constraints for the table.

To delete just delete your schema is a really bad suggestion. There is a problem and it's best to find and fix it.
In my case I was using Envers this creates an Audit table for when entries are updated. But this audit table does not get updated itself it seems when the schema updates (At least not ID and it's relationships)
I just eddited the audit tables offending property and done. Everything back to normal.
To find what the issue is turn the following properties on in application.properties file
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
This will show you what SQL it is trying to executing and hopefully it will provide clarity on real issue.

Add a method hashCode() to your Entity Bean Class and retry it

Related

How to avoid duplicate insertions of "many" entity in one-to-many relationship when using a unique constraint in eclipselink/JPA

I am working on a large codebase using Spring MVC with EclipseLink 2.5.2 on a mysql database. The database and its structure are created directly, not through any code-first approach. My problem concerns 2 tables in a one-to-many relationship.
CREATE TABLE ROLE (
ID BIGINT(20) PRIMARY KEY,
-- OTHER FIELDS --
);
CREATE TABLE ROLE_DOMAIN (
ID BIGINT(20) PRIMARY KEY,
ROLE_ID BIGINT(20) NOT NULL,
DOMAIN VARCHAR(255) NOT NULL
-- OTHER FIELDS --
);
ALTER TABLE ROLE_DOMAIN ADD CONSTRAINT FK_ROLE_DOMAIN_ROLE_ID FOREIGN KEY (ROLE_ID) REFERENCES ROLE_BASE (ID) ON DELETE CASCADE;
ALTER TABLE ROLE_DOMAIN ADD CONSTRAINT UQ_ROLE_DOMAIN_ROLE_ID_DOMAIN UNIQUE (ROLE_ID, DOMAIN);
And in java, this is how I've got the two entities configured.
#Entity
public class Role {
private Long id;
private Set<RoleDomain> roleDomains = new HashSet<>();
#Id
#TableGenerator(name = "ROLE.ID", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "ROLE.ID")
public Long getID() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "ROLE_ID", referencedColumnName = "ID", insertable = false, updatable = false)
public Set<RoleDomain> getRoleDomains() {
return roleDomains;
}
public void setRoleDomains(Set<RoleDomain> roleDomains) {
this.roleDomains = roleDomains;
}
}
#Entity
#Table(name = "ROLE_DOMAIN")
public class RoleDomain {
private Long id;
private Long roleId;
private String domain;
#Id
#TableGenerator(name = "ROLE_DOMAIN.ID", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "ROLE_DOMAIN.ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "ROLE_ID", nullable = false)
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
#Column(name = "DOMAIN", length = 255)
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
Say that in this table structure, I already have a record in ROLE and a record in ROLE_DOMAIN that references it, translating to a Role object named myRole containing the RoleDomain in roleDomains.
Now, when I add a new RoleDomain and save using a spring data repository like this:
myRole.add(new RoleDomain("some string"));
roleRepository.save(myRole);
I get an exception for a duplicate insert violating my unique constraint on ROLE_ID and DOMAIN in the database.
[EL Warning]: 2020-10-22 14:53:22.405--UnitOfWork(994047815)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.8.v20190620-d6443d8be7): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '198732-some string' for key 'UQ_ROLE_DOMAIN_ROLE_ID_DOMAIN'
Error Code: 1062
Call: INSERT INTO ROLE_DOMAIN (ID, DOMAIN, ROLE_ID) VALUES (?, ?, ?)
bind => [27, some other string, 198732]
The weirdest thing about this problem is that if I remove the unique constraint from the database (Note: keeping the java annotation configuration EXACTLY the same. Literally just "DROP CONSTRAINT..." in the db) then the save call works just fine. It doesn't create duplicates in ROLE_DOMAIN. It does exactly what it's supposed to, just adds the new record to ROLE_DOMAIN.
I don't understand how a unique constraint in the db would cause eclipselink to act this inconsistently. Do I have something configured wrongly? Thanks.
EDIT:
I have just now tried replacing the #Table annotation on the RoleDomain class with this:
#Table(name = "ROLE_DOMAIN", uniqueConstraints =
#UniqueConstraint(columnNames = {"ROLE_ID", "DOMAIN"}))
It didn't change anything.
The issue with your constraint is that EclipseLink orders statements for batching, putting deletes last - this is to give you a chance to clean up other constraints, to modify existing rows before rows get deleted. This can be changed so that deletes are issued first using the setShouldPerformDeletesFirst method on the UnitOfWork. As this is native api, you will have to unwrap the EntityManager to get at it, using
em.unwrap(org.eclipse.persistence.sessions.UnitOfWork.class)
if you are in a transaction. This will only be set for the UnitOfWork within this EntityManager, so if you need it everywhere always, you will want to have a session listener with your own session adaptor class to listen for postAcquireUnitOfWork and call setShouldPerformDeletesFirst on it.

How to implement Composite Primary key and Composite Foreign Key using JPA,Hibernate, Springboot

I searched a lot for this particular problem but i didn''t find any specific solution. I have a Composite Primary Key in one table and one of the field from this composite primary key is the part of the Composite Primary Key of another table. You can say that this particular field is the foreign key in the second table but i a not defining any exclusive Foreign Key constraint in the table definition. There can be multiple Records in the second table for each rec in the first table.i am trying to implement this using SPringBoot-JPA-Hibernate but not being able to do so. Can some body help me here. Here are the detais:-
I have a USER_CREDENTIAL table with following fields:-
CREATE TABLE `INSTITUTION_USER_CREDENTIAL` (
`INSTITUTION_USER_ID INT(10) NOT NULL, -> AutoGeneratd
`INSTITUTION_USER_NAME` VARCHAR(50) NOT NULL,
`INSTITUTION_USER_PASSWORD` VARCHAR(50) NOT NULL,
`FIRST_NAME` VARCHAR(100) NOT NULL,
`MIDDLE_NAME` VARCHAR(100),
`LAST_NAME` VARCHAR(100) NOT NULL,
PRIMARY KEY (`INSTITUTION_USER_ID`,`INSTITUTION_USER_NAME`)
);
2) Here is my second table
CREATE TABLE `INSTITUTION_USER_CREDENTIAL_MASTER` (
`INSTITUTION_ID` INT(10) NOT NULL, -> Autogenerated
`INSTITUTION_USER_ID` INT(10) NOT NULL, -> Coming from
INSTITUTION_USER_CREDENTIAL
`INSTITUTION_USER_ROLE` CHAR(02) NOT NULL,
`INSTITUTION_USER_STATUS` CHAR(02) NOT NULL,
`INSTITUTION_NAME` VARCHAR(200) NOT NULL,
`LAST_UPDT_ID` VARCHAR(100) NOT NULL,
`LAST_UPDT_TS` DATETIME NOT NULL,
PRIMARY KEY(`INSTITUTION_ID`,`INSTITUTION_USER_ID`,`INSTITUTION_USER_ROLE`)
);
Note that i haven't declare any particular foreign key in the second table. I have two #Embeddable Class corresponding to two primary key structure for two different table:-
For the INSTITUTION_USER_CREDENTIAL table:-
#Embeddable
public class InstitutionUserCredentialPrimaryKey implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "INSTITUTION_USER_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int institutionUserId;
#Column(name = "INSTITUTION_USER_NAME")
private String institutionUserName;
//Getter-Setters removed for clarity
}
Corresponding Entity Class:-
#Entity(name = "INSTITUTION_USER_CREDENTIAL")
public class InstitutionUserCredential {
#EmbeddedId
private InstitutionUserCredentialPrimaryKey
institutionUserCredentialPrimaryKey;
#Column(name = "INSTITUTION_USER_PASSWORD")
private String instituteUserPassword;
#Column(name = "FIRST_NAME")
private String firstname;
#Column(name = "MIDDLE_NAME")
private String middleName;
#Column(name = "LAST_NAME")
private String lastName;
#OneToMany(mappedBy="institutionUserCredential", cascade = CascadeType.ALL)
private List<InstitutionUserCredentialMaster>
institutionUserCredentialMaster;
//Getter-Setter and other part of the code removed for clarity
}
For the INSTITUTION_USER_CREDENTIAL_MASTER table:-
#Embeddable
public class InstituteUserCredentialMasterPrimaryKey implements Serializable
{
private static final long serialVersionUID = 1L;
#Column(name = "INSTITUTION_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int institutionId;
#Column(name = "INSTITUTION_USER_ID")
private int institutionUserId;
#Column(name = "INSTITUTION_USER_ROLE")
private String userRole;
//Getter-Setter and other part of the code removed for clarity
}
Entity Class:-
#Entity(name = "INSTITUTION_USER_CREDENTIAL_MASTER")
public class InstitutionUserCredentialMaster {
#EmbeddedId
private InstituteUserCredentialMasterPrimaryKey
instituteUserCredentialMasterPrimaryKey;
#Column(name = "INSTITUTION_USER_STATUS")
private String userStatus;
#Column(name = "INSTITUTION_NAME")
private String institutionName;
#Column(name = "LAST_UPDT_ID")
private String lastUpdateId;
#Column(name = "LAST_UPDT_TS")
private String lastUpdateTimestamp;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumns({
#JoinColumn(name="institutionUserId", referencedColumnName =
"INSTITUTION_USER_ID")
})
private InstitutionUserCredential institutionUserCredential;
//Getter-Setter and other part of the code removed for clarity
}
Note that only 1 field INSTITUTION_USER_ID, is getting used in the Composite PrimaryKey of the InstitutionUserCredentialMaster and is coming from the composite primary key of the InstitutionUserCredential.
When i am running my code this is giving me an error like :-
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException:
referencedColumnNames(INSTITUTION_USER_ID) of com.bnl.application.entity.InstitutionUserCredentialMaster.institutionUserCredential referencing com.bnl.application.entity.InstitutionUserCredential not mapped to a single property
None of the examples i have seen so far involving the Composite Primary key and foreign key doesn't treat any one particular field and is more of the entire key structure. I am using MYSQL and i have checked that we can create table having composite primary key and one of the field from that composite key is foreign key in another table and also part of the Composite Primary key of the second table.
Any pointers appreciated
UPDATE:- In my first post i made a mistake while posting it. I am sorry that institutionUserName became a part of the InstitutionUserCredentialMaster. it was a typo. There is no existence of the intitutionUserName in the InstitutionUserCredentialMaster table. i have fixed that and updated the post.
***** Update based on the input by Niver and Wega *****
Update to the InstitutionUserCredentialMasterPrimaryKey
#Embeddable
public class InstituteUserCredentialMasterPrimaryKey implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "INSTITUTION_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int institutionId;
#Column(name = "INSTITUTION_USER_ID")
private int institutionUserId;
// Added the institutionUserName
#Column(name = "INSTITUTION_USER_NAME")
private String institutionUserName;
#Column(name = "INSTITUTION_USER_ROLE")
private String userRole;
}
Update to the Entity Class InsstitutionUserCredentialMaster :-
#Entity(name = "INSTITUTION_USER_CREDENTIAL_MASTER")
public class InstitutionUserCredentialMaster {
#EmbeddedId
private InstituteUserCredentialMasterPrimaryKey instituteUserCredentialMasterPrimaryKey;
#Column(name = "INSTITUTION_USER_STATUS")
private String userStatus;
#Column(name = "INSTITUTION_NAME")
private String institutionName;
#Column(name = "LAST_UPDT_ID")
private String lastUpdateId;
#Column(name = "LAST_UPDT_TS")
private String lastUpdateTimestamp;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumns({
#JoinColumn(name="institutionUserId", referencedColumnName = "INSTITUTION_USER_ID"),
#JoinColumn(name="institutionUserName",referencedColumnName = "INSTITUTION_USER_NAME")
})
private InstitutionUserCredential institutionUserCredential;
}
This time i am getting an error like
Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: Table [institution_user_credential_master] contains physical column name [institution_user_id] referred to by multiple physical column names: [institutionUserId], [INSTITUTION_USER_ID]
I think that the problem is that you are not referencing the other part of the EmbeddedId in the JoinColumns annotation. You have defined that also the institutionUserName is part of the primary key, so you should mention it as well in the definition of the foreign key in entity InstitutionUserCredentialMaster.

Hibernate is getting wrong ID values when using UUID as primary key

My entity:
#Entity
#Table(name = "eh_portal")
public class PortalEntity {
#Id
#Column(name = "id", columnDefinition = "CHAR(36)")
private UUID id; //java.util.UUID;
#Column(name = "name")
private String name;
#Column(name = "url")
private String url;
// -- Constructor for Hibernate --
protected PortalEntity() {
}
// -- Constructor for new entity in service code --
public PortalEntity(final UUID id) {
this.id = id;
}
.... getters and setters ommited
}
Respository is Spring DATA JPA:
public interface PortalRepository extends CrudRepository<PortalEntity, UUID> {
}
MYSQL 5 Database table definition:
CREATE TABLE `eh_portal` (
`id` char(36) NOT NULL COMMENT 'UUID',
`name` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `url_UNIQUE` (`url`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The problem is, Hibernate is returning obviously wrong data - see screenshots below
Mysql workbench:
Actual web page where I get entities thru Spring Data JPA:
You can see that UUIDs are obviously differrent, while other columns are correct.
What is wrong here? (Spring 4, Hibernate 4, Spring DATA JPA, Mysql 5)
Try using #Type(type="uuid-char").

Error when persisting entity with foreign key field

I am try persist in database this entity:
#Entity
#Table(name="pessoa_juridica")
public class PessoaJuridica {
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="cnpj")
#Order(value=1)
private String cnpj;
#Column(name="razao_social")
#Order(value=2)
private String razaoSocial;
#OneToOne( fetch = FetchType.EAGER, cascade = {CascadeType.ALL} )
#Order(value=3)
#JoinColumn(name="contato")
private Contato contato;
}
but when I open the view with the form, I get this error:
org.springframework.beans.NullValueInNestedPathException: Invalid property 'pessoaJuridica.contato' of bean class [com.spring.loja.model.cliente.persistence.model.Cliente]: Could not instantiate property type [java.lang.Integer] to auto-grow nested property path:
java.lang.InstantiationException:
java.lang.Integerorg.springframework.beans.BeanWrapperImpl.newValue(BeanWrapperImpl.java:651)
org.springframework.beans.BeanWrapperImpl.createDefaultPropertyValue(BeanWrapperImpl.java:620)
org.springframework.beans.BeanWrapperImpl.setDefaultValue(BeanWrapperImpl.java:609)
org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:574)
org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:548)
org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:549)
org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:714)
org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99)
org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:229)
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_form_005flabel_005f13(fields_jsp.java:2969)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fwhen_005f17(fields_jsp.java:2836)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fchoose_005f3(fields_jsp.java:2583)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fforEach_005f4(fields_jsp.java:2539)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fwhen_005f14(fields_jsp.java:2444)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fchoose_005f0(fields_jsp.java:242)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fforEach_005f0(fields_jsp.java:150)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspService(fields_jsp.java:115)org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:954)org.apache.jsp.WEB_002dINF.jsp.private_.cadastrar_jsp._jspx_meth_form_005fform_005f0(cadastrar_jsp.java:166)org.apache.jsp.WEB_002dINF.jsp.private_.cadastrar_jsp._jspService(cadastrar_jsp.java:88)org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1217)org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)javax.servlet.http.HttpServlet.service(HttpServlet.java:621)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
the setter/getter methods for Contato are:
public Integer getContato() {
return contato.getId();
}
public void setContato(Integer id) {
this.contato = new Contato(id);
}
the class Contatois this:
#Entity
#Table(name="contato")
public class Contato {
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="nome", unique=true)
#Order(value=1)
private String nome;
#Column(name="email")
#Order(value=2)
private String email;
#Column(name="telefone")
#Order(value=3)
private String telefone;
public Contato() {
this.id = null;
this.nome = null;
this.email = null;
this.telefone = null;
}
public Contato(Integer id) {
this.id = id;
}
}
If I try this for the setter/getter method:
public Contato getContato() {
return contato;
}
public void setContato(Contato contato) {
this.contato = contato;
}
the view is opened, but when I try submit the form, I get the error:
org.hibernate.PersistentObjectException: detached entity passed to persist: com.spring.loja.model.contato.persistence.model.Contatoorg.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:314)org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:432)org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:314)org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:432)org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)com.spring.loja.config.generic.persistence.Dao.persist(Dao.java:32)com.spring.loja.config.generic.persistence.Dao$$FastClassBySpringCGLIB$$ddbbe880.invoke(<generated>)org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)com.spring.loja.model.cliente.persistence.ClienteHome$$EnhancerBySpringCGLIB$$83cbd101.persist(<generated>)com.spring.loja.config.generic.service.service.cadastra(service.java:45)com.spring.loja.config.generic.service.service$$FastClassBySpringCGLIB$$c92a3159.invoke(<generated>)org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)com.spring.loja.model.cliente.service.ClienteService$$EnhancerBySpringCGLIB$$71ccd54c.cadastra(<generated>)com.spring.loja.config.generic.controller.controller.cadastra(controller.java:42)com.spring.loja.config.generic.controller.controller$$FastClassBySpringCGLIB$$c8cc444b.invoke(<generated>)org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:640)com.spring.loja.model.cliente.controller.ClienteController$$EnhancerBySpringCGLIB$$ffe13d4e_2.cadastra(<generated>)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:606)org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)javax.servlet.http.HttpServlet.service(HttpServlet.java:647)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
anyone knows the right way to persist the entity?
UPDATE
the field contato is mapped on the view as this:
<form:label path="pessoaJuridica.contato.id" class="label label-default">contato</form:label>
<form:select path="pessoaJuridica.contato.id" class="form-control select embed" data-lista="${url}" data-altera="${altera}" data-remove="${remove}"/>
UPDATE 2
In database, this is the how tables are created:
CREATE TABLE pessoa_juridica
(
id serial NOT NULL,
cnpj character varying(255),
razao_social character varying(255),
contato integer,
CONSTRAINT pessoa_juridica_pkey PRIMARY KEY (id),
CONSTRAINT fk_eaa4oxajsuofatiyag213dio9 FOREIGN KEY (contato)
REFERENCES contato (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE pessoa_juridica
OWNER TO klebermo;
CREATE TABLE contato
(
id serial NOT NULL,
email character varying(255),
nome character varying(255),
telefone character varying(255),
CONSTRAINT contato_pkey PRIMARY KEY (id),
CONSTRAINT uk_rrtn7wgfxo0jfwkhby23f72cn UNIQUE (nome)
)
WITH (
OIDS=FALSE
);
ALTER TABLE contato
OWNER TO klebermo;
As I remember, the join column name is not the name of the object you are joining to, but the name of the column on the object you are joining to.
You told JPA to cascade all! and passed detached object to save, that is an issue.
According to Hibernate.
CascadeType.PERSIST: cascades the persist (create) operation to
associated entities persist() is called or if the entity is managed
You said #OneToOne( fetch = FetchType.EAGER, cascade = {CascadeType.ALL} ) means it will apply all Transitive persistence.
So removing cascade = {CascadeType.ALL} will solve the prob.
#OneToOne( fetch = FetchType.EAGER)
#Order(value=3)
#JoinColumn(name="contato")
private Contato contato;

How to resolve hibernate table creation while its says unsuccessful creating table

I have a domain class name DataList
#Entity
#Table(name = "list_data")
public class ListData {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "sys_id")
private String sysId;
#Column(name = "name")
private String name;
#Column(name = "detail")
private String detail;
#Column(name = "values")
private String values;
//getters and setters
}
I have some others domain class..
I'm using hibernate 3.6 everything alright.
but somehow Im unsuccessful while creating this table.
2012-02-25 03:31:52,166 ERROR SchemaExport:274 Unsuccessful: create table list_data (id >integer not null auto_increment, detail varchar(255), name varchar(255), sys_id varchar(255), >values varchar(255), primary key (id))
2012-02-25 03:31:52,167 ERROR SchemaExport:275 You have an error in your SQL syntax; check the >manual that corresponds to your MySQL server version for the right syntax to use near 'values >varchar(255), primary key (id))' at line 1
I know my hibernate configuration is fine, I have some other domain class, they are working just fine.
I think that you cannot use values as a column name since it is a MySQL keyword (INSERT INTO ... VALUES() ).

Categories