hibernate4注解方式相关配置

hibernate4注解方式配置和XML方式配置差不多

不同之处

1.添加jar包slf4j-simple.jar(太费事,贴图啦)

hibernate4注解方式相关配置_第1张图片

2.去掉 User.hbm.xml文件
3.实体中添加注解
4.修改hibernate.cfg.xml中的映射文件
5.修改测试文件中SessionFactory的创建方式

详细代码例子

1.实体创建
/hibernate_test/src/com/test/domin/User.java

package com.test.domin;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

2.配置文件
/hibernate_test/config/hibernate.cfg.xml


 

 <hibernate-configuration>
        <session-factory>

         
         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>
         
         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testproperty>
         
         <property name="hibernate.connection.username">rootproperty>
         
         <property name="connection.password">rootproperty>
         
         
         
         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>

         <property name="hbm2ddl.auto">updateproperty>

         
         <property name="show_sql">trueproperty>
         
         
         
         <property name="current_session_context_class">threadproperty>

         
         <mapping class="com.test.domin.User"/>
     session-factory>
 hibernate-configuration>

测试文件
/hibernate_test/test/test/HibernateTest.java

package test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.test.domin.User;

public class HibernateTest {
    @Test
    public void testHibernateEnv() {
        Configuration config = new AnnotationConfiguration();
        config.configure();
        SessionFactory sessionFactory = config.buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        User user = new User();
        user.setUsername("test2");
        user.setPassword("12342");
        session.save(user);
        System.out.println("保存成功");
        session.getTransaction().commit();
    }
}

好啦,大功告成,散花庆祝。新手上路,请多多包涵。

你可能感兴趣的:(hibernate学习笔记)