1. 程式人生 > >Hibernate整合Spring(java專案)

Hibernate整合Spring(java專案)

1、首先需要建立一個maven的java專案,新增對應的依賴(4個Spring的依賴和一個hibernate的依賴)pom.xml檔案如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.iflytek</groupId>
  <artifactId>firstSpringHibernate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.3.13.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.13.RELEASE</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-orm</artifactId>
		    <version>4.3.13.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.3.13.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.11.Final</version>
		</dependency>
		
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
  
</project>
儲存之後在手動buildpath新增ojdbc的驅動,之後會得到如下圖的jar檔案

2、新增配置檔案applicationContext.xml檔案,配置資料庫的驅動連線和sessionFactory的初始化物件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
        <!-- 配置可以使用Spring註解 -->
    <context:component-scan base-package="com.iflytek"></context:component-scan>
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@172.16.130.35:1521:orcl"></property>
		<property name="username" value="uuid"></property>
		<property name="password" value="uuid"></property>
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="packagesToScan" value="com.iflytek.domain"></property>
		<property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
		</property>
	</bean>
	
	
</beans>
對應的還有其他屬性檔案,這裡還有用log4j.property的日誌檔案,列印日誌的,意義不大,所以不多做說明了。

3、寫java pojo的程式碼配置註釋生成對應的資料庫表

(也可以通過hbm.xml檔案配置資料表,但是需要在在ApplicationContext.xml檔案中配置sessionfatcory加上如下:

 <property name="mappingResources">

        <list>

           <value>xxx/xxx/model/User.hbm.xml</value>

        </list
>
</property> <property name="hibernateProperties">
,這裡用註解的方法生成

User類

package com.iflytek.domain;

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

//把user物件建立(預設的名字為:物件的名字小寫),然後加入到容器中
@Entity
@Table(name="t_user1")
public class User {

	private int id;
	
	private String name;

	@Id
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
4、寫java程式碼需要的其他檔案,如service層,dao層和測試類等

UserService.java

package com.iflytek.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.iflytek.dao.UserDao;

@Service
public class UserService {
	
	@Resource
	private UserDao userDao;

	public UserService() {
	}
	public UserService(UserDao userDao) {
		this.userDao = userDao;
		System.out.println("userservice construct run...");
	}
	
}

UserDao.java

package com.iflytek.dao;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.iflytek.domain.User;

@Repository
public class UserDao {
	
	@Resource
	private SessionFactory sessionFactory;

	public void save() {
		
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();

		User user = new User();
		user.setId(1001);
		user.setName("testsaveuser");
		
		session.save(user);
		
		tx.commit();
		session.close();
		
	}
}

測試類App.java

package com.iflytek.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.iflytek.dao.UserDao;

public class App {

	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		UserDao bean = context.getBean(UserDao.class);
		
		bean.save();
	}
}

5、結果

會在資料庫中生成一張t_user1的資料表,新增一條id為1001的資料,如下圖


綜:存初學者個人學習,相互交流,不喜勿噴。