零xml配置Hibernate:使用hibernate.properties代替hibernate.cfg.xml

之前写了一篇零xml配置Spring声明式事务,接下来写一下如何零xml配置Hibernate

Spring实战和Hibernate实战这两本书的作者都推荐使用注解的方式来代替xml配置。但在Hibernate实战中,作者还是使用了hibernate.cfg.xml 来配置连接数据库时的一些信息,然而我还是喜欢完全使用Java的配置,但有没有其他方法来代替hibernate.cfg.xml 呢?答案是肯定的。

最直接的途径就是看官方文档,然而官网也是使用hibernate.cfg.xml,继续往下看,直到看到了官方配置SessionFactory的示例

官方示例

protected void setUp() throws Exception {
    // A SessionFactory is set up once for an application!
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .configure() // configures settings from hibernate.cfg.xml
            .build();
    try {
        sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
    }
    catch (Exception e) {
        // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
        // so destroy it manually.
        StandardServiceRegistryBuilder.destroy( registry );
    }
}

里面的configure() 方法是用来加载hibernate.cfg.xml 的,但能不能加载其他类型的文件呢?

查看StandardServiceRegistryBuilder API,发现configure()只能用来加载XML文件

    /**
     * Read setting information from an XML file using the standard resource location.
     *
     * @return this, for method chaining
     *
     * @see #DEFAULT_CFG_RESOURCE_NAME
     * @see #configure(String)
     * @see #loadProperties(String)
     */
    public StandardServiceRegistryBuilder configure() {
        return configure( DEFAULT_CFG_RESOURCE_NAME );
    }

    /**
     * Read setting information from an XML file using the named resource location.
     *
     * @param resourceName The named resource
     *
     * @return this, for method chaining
     */
    public StandardServiceRegistryBuilder configure(String resourceName) {
        return configure( configLoader.loadConfigXmlResource( resourceName ) );
    }

    public StandardServiceRegistryBuilder configure(File configurationFile) {
        return configure( configLoader.loadConfigXmlFile( configurationFile ) );
    }

    public StandardServiceRegistryBuilder configure(URL url) {
        return configure( configLoader.loadConfigXmlUrl( url ) );
    }

    @SuppressWarnings( {"unchecked"})
    public StandardServiceRegistryBuilder configure(LoadedConfig loadedConfig) {
        aggregatedCfgXml.merge( loadedConfig );
        settings.putAll( loadedConfig.getConfigurationValues() );

        return this;
    }

继续看API,终于找到了一个方法loadProperties() ,这不就是在JDBC里经常使用的properties 文件吗!

    /**
     * Read settings from a {@link java.util.Properties} file by resource name.
     *
     * Differs from {@link #configure()} and {@link #configure(String)} in that here we expect to read a
     * {@link java.util.Properties} file while for {@link #configure} we read the XML variant.
     *
     * @param resourceName The name by which to perform a resource look up for the properties file.
     *
     * @return this, for method chaining
     *
     * @see #configure()
     * @see #configure(String)
     */
    @SuppressWarnings( {"unchecked"})
    public StandardServiceRegistryBuilder loadProperties(String resourceName) {
        settings.putAll( configLoader.loadProperties( resourceName ) );
        return this;
    }

    /**
     * Read settings from a {@link java.util.Properties} file by File reference
     *
     * Differs from {@link #configure()} and {@link #configure(String)} in that here we expect to read a
     * {@link java.util.Properties} file while for {@link #configure} we read the XML variant.
     *
     * @param file The properties File reference
     *
     * @return this, for method chaining
     *
     * @see #configure()
     * @see #configure(String)
     */
    @SuppressWarnings( {"unchecked"})
    public StandardServiceRegistryBuilder loadProperties(File file) {
        settings.putAll( configLoader.loadProperties( file ) );
        return this;
    }

找到了能代替hibernate.cfg.xml的方法,接下来就是配置了

首先创建一个hibernate.properties 文件,配置连接数据库的信息

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql:///hibernate?useUnicode=true&;characterEncoding=UTF-8
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.username=root
hibernate.connection.password=1111111
#是否把Hibernate运行时的SQL语句输出到控制台,编码阶段易于测试
hibernate.show_sql=true
#输出到控制台的SQL语句是否进行排版,便于阅读
hibernate.format_sql=true
#帮助由Java代码生成数据库脚本,create表示如果原来的表存在,则先删除在新建一个
hibernate.hbm2ddl.auto=create

创建一个实体类


@Entity
@Table(name = "Students")
public class Student {

    @Id
    private String sid; //学号
    private String sname; //姓名
    private String gender; //性别
    @Temporal(value = TemporalType.DATE)
    private Date birthday; //出生日期
    private String address; //地址

    public Student() {}

    public Student(String sid, String sname, String gender, Date birthday, String address) {
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.address = address;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" + "sid=" + sid + ", sname='" + sname + '\'' + ", gender='" + gender + '\'' + ", birthday=" + birthday + ", address='" + address + '\'' + '}';
    }
}

创建一个测试类

public class StudentTest {
    private static final String FILEPATH="src/main/java/hibernate/hibernate.properties";
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void init(){
        File file=new File(FILEPATH);
        //创建服务注册对象
        final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
                //加载Hibernate配置文件
                .loadProperties(file)
                .build();

        //创建会话工厂对象
        //SessionFactory sessionFactory=conf.buildSessionFactory();
        sessionFactory=new MetadataSources(registry)
                //将持久化类添加到元数据源
                .addAnnotatedClass(Student.class)
                .buildMetadata().buildSessionFactory();
        //打开会话
        session=sessionFactory.openSession();
        //打开事务
        transaction=session.beginTransaction();
    }

    @Test
    public void testSaveStudents(){
        Student student=new Student("100000","jack","male",new Date(),"NewYork");
        session.save(student); //保存对象到数据库
    }

    @After
    public void destroy(){
        transaction.commit();
        session.close();
        sessionFactory.close();
    }
}

loadProperties() 接收两种参数,File 或者 String ,这里我用了File ,使用String 只传入hibernate.properties 文件的路径更方便

这样就实现了零xml配置Hibernate。个人觉得配置hibernate.properties 要比 hibernate.cfg.xml 方便,只需要直接写基本的信息,而不需要写xml的标签等等的。





参考:
http://blog.csdn.net/qwe6112071/article/details/51013386
https://www.tutorialspoint.com/hibernate/hibernate_configuration.htm
http://blog.csdn.net/adverse/article/details/1541221
http://www.2cto.com/kf/201411/349872.html

你可能感兴趣的:(java)