示例代码:http://download.csdn.net/detail/u010476739/9922870
工具:maven、spring framework4、hibernate4、postgresql
1.准备数据库,使用postgresql
CREATE TABLE Student(
ID SERIAL PRIMARY Key,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL
);
2.新建项目,添加依赖
<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.jackletter</groupId>
<artifactId>spring-hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>this is name</name>
<description>this is desc</description>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<postgresql.version>9.1-901.jdbc4</postgresql.version>
<hibernate.version>4.3.11.Final</hibernate.version>
</properties>
<dependencies>
<!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Aop -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-aop/4.3.4.RELEASE -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<!-- Hibernate4 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies>
</project>
3.spring配置(applicationContext.xml)
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:component-scan base-package="bean" />
<!-- Initialization for data source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/Demo" />
<property name="username" value="postgres" />
<property name="password" value="huqingjie123" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false">
<!-- 注入datasource,给sessionfactoryBean内setdatasource提供数据源 -->
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<!-- //加载实体类的映射文件位置及名称 -->
<property name="mappingLocations" value="classpath:bean/*.hbm.xml"></property>
</bean>
<!-- 配置Spring声明式事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务事务属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切点,并把切点和事务属性关联起来 -->
<aop:config>
<aop:pointcut expression="execution(* bean.StudentDAO.*(..))" id="txPointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
4.hibernate配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置Hibernate的基本属性 -->
<!-- 1.数据源配置到IOC容器中 -->
<!-- 2.关联的.hbm.xml也在IOC容器配置SessionFactory实例 -->
<!-- 3.配置Hibernate的基本属性:方言,SQL显示及格式化,生成数据表的策略以及二级缓存 -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
5.代码
Student
package bean;
import javax.persistence.Entity;
@Entity
public class Student {
private Integer age;
private String name;
private Integer id;
public Student(Integer age, String name) {
super();
this.age = age;
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentDAO
package bean;
public interface StudentDAO {
public String findStudentById(int id);
public void saveStudent(Student student);
}
StudentDaoImpl
package bean;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class StudentDaoImpl implements StudentDAO {
@Autowired
private SessionFactory sessionFactory;
// 获取和当前线程绑定的Seesion
private Session getSession() {
return sessionFactory.getCurrentSession();
}
public String findStudentById(int id) {
String hql = "SELECT name from Student where id=?";
Query query = getSession().createQuery(hql).setInteger(0, id);
String str = query.uniqueResult().toString();
return str;
}
public void saveStudent(Student student) {
getSession().save(student);
}
}
StudentService
package bean;
public interface StudentService {
public String findStudentById(int id);
public void saveStudent(Student student);
}
StudentServiceImpl
package bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
public String findStudentById(int id) {
return studentDao.findStudentById(id);
}
public void saveStudent(Student book) {
studentDao.saveStudent(book);
}
}
App
package springhibernate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.Student;
import bean.StudentService;
public class App {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService srv=context.getBean(StudentService.class);
srv.saveStudent(new Student(25,"lisa"));
srv.saveStudent(new Student(27,"xiaogang"));
srv.saveStudent(new Student(30,"tom"));
srv.saveStudent(new Student(18,"jack"));
String studentName=srv.findStudentById(1);
System.out.println(studentName);
}
}