对 basic type attributes, JPA implicit naming rule 为: column name 即是 attribute name
可以使用 @Column 显式指定 column name
package org.example.demo.hibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
factory.close();
}
@Entity(name = "Product")
public static class Product {
@Id
Integer id;
String sku;
String name;
@Column(name = "NOTES")
String description;
}
}
生成的 SQL
drop table if exists Product cascade
create table Product (id int4 not null, NOTES varchar(255), name varchar(255), sku varchar(255), primary key (id))
如果先生成表
drop table if exists Person cascade;
drop sequence if exists hibernate_sequence;
create sequence hibernate_sequence start 1 increment 1;
create table Person (id int8 not null, name varchar(255), primary key (id));
然后修改 src/main/resources/META-INF/persistence.xml 去除 javax.persistence.schema-generation.database.action
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="test">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:p6spy:postgresql://localhost:5432/test" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="postgres" />
</properties>
</persistence-unit>
</persistence>
然后执行
package org.example.demo.hibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist(new Person());
em.getTransaction().commit();
em.close();
factory.close();
}
@Entity(name = "Person")
public static class Person {
@Id
@GeneratedValue
Long id;
@Column(nullable = false)
String name;
}
}
第 17 行也抛异常 javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value : org.example.demo.hibernate.Test$Person.name
即 Hibernate 不管数据库是否有 not null 约束,只要 @Column.nullable = false 则会检查是否 null