【发布时间】:2018-02-18 08:05:57
【问题描述】:
我正在学习 Java 和 Hibernate。现在,我很难理解如何使用自定义物理命名策略:虽然 PhysicalNamingStrategy 对象确实已实例化,但从未调用过 toPhysicalTableName 或 toPhysicalColumnName 方法——这不是我可以用调试器看到的,至少。
版本:Java 1.8、Hibernate 5.2.10.Final、macOS 10.12。
这是一个最小的项目:
@Entity
public class Cake {
@Id
private long id;
private String name;
private String FLAVOUR;
private int sErViNg;
public Cake(String name, String flavour, int serving) {
this.name = name;
this.FLAVOUR = flavour;
this.sErViNg = serving;
}
// getters and setters
public class Main {
public static void main (String[] args) {
Transaction tx = null;
try (
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
) {
tx = session.beginTransaction();
Cake cake = new Cake("Molten Chocolate Cake", "chocolate", 1);
session.save(cake);
tx.commit();
}
catch (Exception e) {
e.printStackTrace();
if ( tx != null ) {
tx.rollback();
}
}
}
}
public class AllCapsPhysicalNamingStrategy
extends PhysicalNamingStrategyStandardImpl implements Serializable {
public static final AllCapsPhysicalNamingStrategy INSTANCE
= new AllCapsPhysicalNamingStrategy();
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
return new Identifier(name.getText().toUpperCase(), name.isQuoted());
}
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
return new Identifier(name.getText().toUpperCase(), name.isQuoted());
}
}
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/cake</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.physical_naming_strategy">com.example.AllCapsPhysicalNamingStrategy</property>
<mapping class="com.example.Cake"/>
</session-factory>
</hibernate-configuration>
这是我得到的表格:
[cake]> SELECT * FROM cake;
+----+-----------+-----------------------+---------+
| id | FLAVOUR | name | sErViNg |
+----+-----------+-----------------------+---------+
| 0 | chocolate | Molten Chocolate Cake | 1 |
+----+-----------+-----------------------+---------+
我希望:
+----+-----------+-----------------------+---------+
| ID | FLAVOUR | NAME | SERVING |
+----+-----------+-----------------------+---------+
| 0 | chocolate | Molten Chocolate Cake | 1 |
+----+-----------+-----------------------+---------+
我在这里做错了什么?
【问题讨论】:
-
您使用的是哪个版本的 Hibernate?
-
编辑了我手头的尽可能多的细节。以后有小版本。
-
看来您的原始代码/配置应该可以工作。我假设您在 hibernate.cfg.xml 文件中仔细检查了
AllCapsPhysicalNamingStrategy的完全限定路径是否正确。 -
@SteveChambers 我做到了。如果不是,hibernate 理所当然地抱怨
AllCapsPhysicalNamingStrategy不是PhysicalNamingStrategy的实例。
标签: java hibernate configuration