在关于Hibernate学习过程中,创建服务注册对象无法实现的问题,这主要是因为老版本的方法已经弃用了,采用ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();
进行创建服务注册对象
全页代码如下:
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
//测试类
public class StudentsTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init() {
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();
//创建对话工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
//回话对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction();
}
@After
public void destory() {
transaction.commit(); //提交事务
session.close(); //关闭会话
sessionFactory.close(); //关闭会话工厂
}
@Test
public void testSaveStudents() {
Students s = new Students(2, "张三丰", "男", new Date(), "武当山");
session.save(s); //保存对象进入数据库
}
}
同时在hibernate.cfg.xml中配置也存在问题,当需要使用支持事务的数据库方言,并且使用了mysql 5.5及以上版本时,需要将数据库方言配置为<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
1
注意是MySQL5InnoDBDialect,而不是MySQLInnoDBDialect,否则不能自动建表。
另外附上各种数据库对应的方言:
数据库 方言(Dialect)
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
MySQL5 org.hibernate.dialect.MySQL5Dialect
MySQL5 with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle(any version) org.hibernate.dialect.OracleDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
Oracle 10g org.hibernate.dialect.Oracle10gDialect
Oracle 11g
org.hibernate.dialect.Oracle10gDialect
Sybase
org.hibernate.dialect.SybaseASE15Dialect
Sybase Anywhere
org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server 2000
org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005
org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008
org.hibernate.dialect.SQLServer2008Dialect
SAP DB
org.hibernate.dialect.SAPDBDialect
Informix
org.hibernate.dialect.InformixDialect
HypersonicSQL
org.hibernate.dialect.HSQLDialect
H2 Database
org.hibernate.dialect.H2Dialect
Ingres
org.hibernate.dialect.IngresDialect
Progress
org.hibernate.dialect.ProgressDialect
Mckoi SQL
org.hibernate.dialect.MckoiDialect
Interbase
org.hibernate.dialect.InterbaseDialect
Pointbase
org.hibernate.dialect.PointbaseDialect
FrontBase
org.hibernate.dialect.FrontbaseDialect
Firebird
org.hibernate.dialect.FirebirdDialect
共同学习,写下你的评论
评论加载中...
作者其他优质文章