Spring4+Hibernate4+Maven整合

记录一下自己通过网上查找和摸索回来的spring4和hibernate4的整合,包管理工具用的是Maven,数据库用的是Mysql。

  • 项目目录结构
  • pom.xml文件
  • 配置属性文件
  • spring配置文件application.xml
  • 自定义HibernateUtils工具类
  • pom.xml文件
  • 基本CRUD操作
      创建Person实体类
      创建PersonDao Dao层
      创建PersonService Service层
  • 单元测试

文件目录结构


Spring4+Hibernate4+Maven整合_第1张图片

pom.xm 文件


        UTF-8
        1.8
        4.3.0.RELEASE
        4.3.11.Final
        5.1.38
        4.12
    

    
        
            junit
            junit
            ${junit.version}
            test
        

        
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-beans
            ${spring.version}
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-orm
            ${spring.version}
        
        
            org.springframework
            spring-test
            ${spring.version}
        

        
        
            org.hibernate
            hibernate-core
            ${hibernate.version}
        
        
            org.hibernate
            hibernate-c3p0
            ${hibernate.version}
        
        
            org.aspectj
            aspectjweaver
            1.8.13
        

        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        

    

    
        
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.3.2
                
                    ${project.jdk.version}
                    ${project.jdk.version}
                
            
        
    

配置属性文件

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc\:mysql\://localhost\:3306/db_test?useUnicode\=true&characterEncoding\=UTF-8
jdbc.username = root
jdbc.password = 123456

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true

spring配置文件application.xml



    

    

    
        
        
        
        
        
        
        
        
    

    
    
        
        
        
            
                
                ${hibernate.hbm2ddl.auto}

                
                ${hibernate.dialect}

                
                ${hibernate.show_sql}

                
                ${hibernate.format_sql}
            
        
    

    
    
        
    

    
    

    
    
    

    
        
    

自定义HibernateUtils工具类

public class HibernateUtils {
    public static final ThreadLocal threadLocal= new ThreadLocal();
    
    public static SessionFactory sessionFactory;
    
    public void init(){
        System.out.println("...... 初始化 ......" );
    }
    
    /**
     * 获取当前的Session
     * @return
     */
    public static Session currentSession(){
        Session session = (Session) threadLocal.get();
        if(ObjectUtils.isEmpty(session)){
            session = sessionFactory.getCurrentSession();
            threadLocal.set(session);
        }
        return session;
    }
    
    /**
     * 释放Session
     */
    public static void closeSession(){
        Session session = (Session) threadLocal.get();
        if(ObjectUtils.isEmpty(session)){
            session.close();
        }
        threadLocal.set(null);
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void setSessionFactory(SessionFactory sessionFactory) {
        HibernateUtils.sessionFactory = sessionFactory;
    }

    public static ThreadLocal getThreadlocal() {
        return threadLocal;
    }   
}

创建Person实体类

@Entity
@Table(name = "db_person")
public class Person {
    @Id
    @GeneratedValue
    @Column(name = "PK_ID")
    private int pkId;
    
    @Column(name = "NAME")
    private String name;
    
    @Column(name = "AGE")
    private int age;
    
    @Column(name = "ADDRESS")
    private String address;
    
    public int getPkId() {
        return pkId;
    }
    public void setPkId(int pkId) {
        this.pkId = pkId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Person [pkId=" + pkId + ", name=" + name + ", age=" + age + ", address=" + address + "]";
    }
}

创建PersonDao Dao层


@Repository
public class PersonDao extends BaseDao {
    
    @Override
    public void insert(Person entity) {
        HibernateUtils.currentSession().save(entity);
    }

    @Override
    public Person get(int pkId) {
        return (Person) HibernateUtils.currentSession().get(Person.class, pkId);
    }
    
    @Override
    public List getLists() {
        String hql = "from Person";
        Query query = HibernateUtils.currentSession().createQuery(hql);
        return query.list();
    }

    @Override
    public void Delete(int pkId) {
        Person person = get(pkId);
        HibernateUtils.currentSession().delete(person);
    }

    @Override
    public void update(Person entity) {
        HibernateUtils.currentSession().update(entity);
    }
}

创建PersonService Service层

@Service
public class PersonService {

    @Autowired
    PersonDao personDao;
    
    @Transactional
    public void insert(Person person) {
        personDao.insert(person);
    }

    @Transactional
    public void delete(int pkId) throws Exception {
        personDao.Delete(pkId);
    }

    @Transactional
    public void update(Person person) {
        personDao.update(person);
    }

    @Transactional
    public void get(int pkId) {
        System.out.println("======打印数据======" + personDao.get(pkId));
    }

    @Transactional
    public void getLists() {
        List list = personDao.getLists();
        for (Person person : list) {
            System.out.println("====== 打印数据 =====" + person);
        }
    }
}

单元测试


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/application.xml"})
public class OneTest {
    
    @Autowired
    PersonService personService;
    
    @Test
    public void insert() {
        Person person = new Person();
        person.setName("王五");
        person.setAge(23);
        person.setAddress("中华人民共和国");
        person.setPkId(26);
        personService.insert(person);
    }

    @Test
    public void delete() throws Exception {
        personService.delete(25);
    }

    @Test
    public void update() {
        Person person = new Person();
        person.setPkId(15);
        personService.update(person);
    }

    @Test
    public void get() {
        personService.get(22);
    }

    @Test
    public void getLists() {
        personService.getLists();
    }
}

此文章并非原创 ,部分摘抄自网上资源。

你可能感兴趣的:(Spring4+Hibernate4+Maven整合)