spring+spring MVC+hibernate
先导入hibernate依赖包
<!-- hibernate配置-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernateVersion}</version>
</dependency>
我们使用c3p0的连接池管理数据库连接配合hibernate使用
<!-- 数据库连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0Version}</version>
</dependency>
注意:依赖包版本信息请自己在<properties></properties>中注明
接着我们准备hibernate的配置文件(properties),包括了数据库配置
#database connection config
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hibernate_test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=1
#hibernate config
#dialect:配置方言,根据不同方言生成不同sql语句
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
接下来我们去spring的配置文件中配置数据源、session工厂和事务
<!--扫描配置文件此处***表示你的hibernate配置文件的名字-->
<context:property-placeholder location="classpath:/***.properties" />
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxPoolSize" value="40" /> <!--最大连接数-->
<property name="minPoolSize" value="1" /> <!--最小连接数-->
<property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接-->
<property name="maxIdleTime" value="20" /> <!--最大空闲时间-->
</bean>
<!--配置session工厂-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ssh.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
<prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言-->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句-->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式)-->
</props>
</property>
</bean>
<!-- 事物管理器配置 -->
<!-- 5.事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--6.事务-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
最后在web.xml文件中引入spring的配置文件
<!--加载Spring的配置文件到上下文中去-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-context.xml
</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
到这里整合已经完成了
我们来建一张表
@Entity
//name的值是数据库表名
@Table(name = "Person")
public class Person {
//主键
@Id
//自动生成值
@GeneratedValue
private Integer id;
//列名
@Column(name = "name")
private String name;
//列名
@Column(name = "age")
private Integer age;
public Person() {
}
public Person(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
下面写一个Dao的实现类,Dao就略过了
@Repository
public class PersonDaoImpl implements PersonDao {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.openSession();
}
public Person load(Integer id) {
return (Person) getCurrentSession().load(Person.class, id);
}
public Person get(Integer primaryKey) {
return (Person) getCurrentSession().get(Person.class, primaryKey);
}
public Integer save(Person entity) {
return (Integer) getCurrentSession().save(entity);
}
public void delete(Integer id) {
//查询需要删除的对象
Person person = get(id);
Session session = null;
//事务对象
Transaction ts = null;
try {
session = getCurrentSession();
//开启事务
ts = session.beginTransaction();
session.delete(person);
ts.commit();
} catch (Exception e) {
//回滚
if (ts != null) ts.rollback();
} finally {
//释放资源
if (session != null) session.close();
}
}
public void deleteAll() {
}
public void flush() {
getCurrentSession().flush();
}
public void persist(Person entity) {
getCurrentSession().persist(entity);
}
public void saveOrUpdate(Person entity) {
Session session = null;
Transaction ts = null;
try {
session = getCurrentSession();
ts = session.beginTransaction();
session.saveOrUpdate(entity);
ts.commit();
} catch (Exception e) {
if (ts != null) ts.rollback();
} finally {
if (session != null) session.close();
}
}
public List<Person> getAll() {
Query query = getCurrentSession().createQuery("from Person");
List<Person> list = query.list();
return list;
}
}
通过依赖注入获取到session的对象,使用session对象里面的基础方法来CRUD,基础方法是hibernate已经写好的,参照着他的规范写就行
注意:delete和update操作必须用事务,不然delete和update操作会失效,没有反应
|