欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate 列映射 --名字映射

程序员文章站 2022-04-16 22:42:25
...

– Start
Java 类和数据库表有很多不同,其中之一是类名/字段名与表名/列名可能不一致。如果名字一致,我们无需特殊设置。如果名字不一致,可以使用注解 @Table 和 @Column 手动映射它们之间的关系,我们也可以实现一个命名策略,这样我们就不需要手动配置每个类。

package shangbo.hibernate.demo008;

public class App {
	public static void main(String[] args) throws Exception {
		DataService dataService = new DataService();
		dataService.saveCustomer(new Customer("test"));
	}
}

package shangbo.hibernate.demo008;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

@Entity
//@Table(name = "CUSTOMER")
public class Customer {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="customerId-generator")
	@SequenceGenerator(name="customerId-generator", sequenceName="CUSTOMER_ID_SEQ")
//	@Column(name = "CUSTOMER_ID")
	@Type(type = "int")
	private Integer customerId;

//	@Column(name = "CUSTOMER_NAME")
	@Type(type = "string")
	private String customerName;

	public Customer() {
	}

	public Customer(String customerName) {
		this.customerName = customerName;
	}

	public Integer getCustomerId() {
		return customerId;
	}

	// 主键自动生成,无需 setter 方法
//	public void setCustomerId(Integer customerId) {
//		this.customerId = customerId;
//	}

	public String getCustomerName() {
		return customerName;
	}

	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}
}

package shangbo.hibernate.demo008;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class DataService {
	public void saveCustomer(Customer customer) {
		// 第一步:构造 ServiceRegistry
		StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure(ClassLoader.getSystemResource("shangbo/hibernate/demo008/hibernate.cfg.xml")).build();

		// 第二步:构造 Metadata
		Metadata metadata = new MetadataSources(registry).getMetadataBuilder().applyPhysicalNamingStrategy(new MyPhysicalNamingStrategy()).build();

		// 第三步:构造 SessionFactory
		SessionFactory sessionFactory = metadata.buildSessionFactory();

		// 操作数据库
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(customer);
		session.getTransaction().commit();
		session.close();

		// 关闭 SessionFactory
		sessionFactory.close();
	}
}

package shangbo.hibernate.demo008;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;

public class MyPhysicalNamingStrategy implements PhysicalNamingStrategy {

	@Override
	public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		return name;
	}

	@Override
	public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		return name;
	}

	@Override
	public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		String newName = camltoUnderscore(name.getText());
		return jdbcEnvironment.getIdentifierHelper().toIdentifier(newName, name.isQuoted());
	}

	@Override
	public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		return name;
	}

	@Override
	public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		String newName = camltoUnderscore(name.getText());
		return jdbcEnvironment.getIdentifierHelper().toIdentifier(newName, name.isQuoted());
	}

	private String camltoUnderscore(String name) {
		StringBuilder joined = new StringBuilder();

		for (String part : StringUtils.splitByCharacterTypeCamelCase(name)) {
			joined.append(part).append("_");
		}

		joined.setLength(joined.length() - 1);
		return joined.toString();
	}

}

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">hr</property>
        <property name="connection.password">456789</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <mapping class="shangbo.hibernate.demo008.Customer"/>

    </session-factory>

</hibernate-configuration>

– 更多参见:Hibernate 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-06-16
– Written by ShangBo on 2019-06-16
– End