example ejemplos java hibernate jpa persistence

ejemplos - persistence xml java



Hibernar: "Campo ''id'' no tiene un valor predeterminado" (14)

Agregue un método hashCode() a su clase de Entity Bean y hashCode() a intentarlo

Estoy enfrentando lo que creo que es un problema simple con Hibernate, pero no puedo resolverlo (los foros de Hibernate que son inalcanzables ciertamente no ayudan).

Tengo una clase simple que me gustaría persistir, pero sigo recibiendo:

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 ]

El código relevante para la clase persistente es:

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; } }

Y el código de ejecución real es simple:

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(); }

Intenté algunas "estrategias" dentro de la anotación GeneratedValue pero parece que no funciona. ¡Inicializar la id tampoco ayuda! (por ej. Long id = 20L ).

¿Alguien podría arrojar algo de luz?

EDIT 2: confirmado: jugar con @GeneratedValue(strategy = GenerationType.XXX) no lo resuelve

SOLUCIONADO: la recreación de la base de datos resolvió el problema


Eche un vistazo a la estrategia de GeneratedValue . Por lo general, se ve algo así como:

@GeneratedValue(strategy=GenerationType.IDENTITY)


En ocasiones, los cambios realizados en el modelo o en el ORM pueden no reflejarse con precisión en la base de datos incluso después de la ejecución de SchemaUpdate .

Si el error realmente parece carecer de una explicación sensata, intente recrear la base de datos (o al menos crear una nueva) y SchemaExport con SchemaExport .


Esto me pasó con una relación @ManyToMany . He anotado uno de los campos en la relación con @JoinTable , lo @JoinTable y usé el atributo mappedBy en @ManyToMany en su lugar.


Otra sugerencia es verificar que use un tipo válido para el campo autogenerado. Recuerda que no funciona con String, pero funciona con Long:

@Id @GeneratedValue(strategy=GenerationType.AUTO) public Long id; @Constraints.Required public String contents;

La sintaxis anterior funcionó para generar tablas en MySQL usando Hibernate como proveedor JPA 2.0.


Por favor, compruebe si el valor predeterminado para la identificación de la columna en particular table.if no lo hace por defecto


Se lanzó la misma excepción si una tabla de BD tenía una columna no retirada anterior.

Por ejemplo: attribute_id NOT NULL BIGINT(20), y attributeId NOT NULL BIGINT(20),

Después de eliminar el atributo no utilizado, en mi caso, ContractId , se resolvió el problema.


Si desea que MySQL produzca automáticamente claves principales, debe indicarlo al crear la tabla. No tienes que hacer esto en Oracle.

En la clave principal, debe incluir AUTO_INCREMENT . Vea el ejemplo a continuación.

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;

Aquí está la entidad

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; } }


Tuve este problema, por error, tengo lugar la anotación @Transient sobre ese atributo en particular. En mi caso, este error tiene sentido.


Vine aquí debido al mensaje de error, resulta que tenía dos tablas con el mismo nombre.


Yo tuve el mismo problema. Encontré el tutorial Hibernate One-To-One Mapping Example utilizando Foreign Key Annotation y lo seguí paso a paso como a continuación:

Crear una tabla de base de datos con este 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) );

Aquí están las entidades con las tablas de arriba

@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; }

El problema fue resuelto

Aviso: la clave principal debe configurarse en AUTO_INCREMENT


Yo tuve el mismo problema. Estaba usando una tabla de combinación y todo lo que tenía con un campo de Id. De fila y dos claves foráneas. No sé la causa exacta, pero hice lo siguiente

  1. Actualización de MySQL a la comunidad 5.5.13
  2. Cambiar el nombre de la clase y la tabla
  3. Asegúrate de tener códigos hash e iguales métodos

    @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;


debe estar usando la actualización en su propiedad hbm2ddl. realice los cambios y actualícelo en Crear para que pueda crear la tabla.

<property name="hbm2ddl.auto">create</property>

Funcionó para mí


Solo agrega una restricción no nula

Yo tuve el mismo problema. Acabo de agregar una restricción no nula en el mapeo xml. Funcionó

<set name="phone" cascade="all" lazy="false" > <key column="id" not-null="true" /> <one-to-many class="com.practice.phone"/> </set>