在《spring4之搭建restful风格的web服务》一文的基础上和hibernate5快速集成,达到restful的控制器调用DAO操作数据库的目标。
当然,在此基础上可以继续进化为控制器调动service层,事务控制在service层,由service调用DAO完成数据库操作,那就是下一步的事情了。
准备lib
下载hibernate5.2.4,解压后拷贝lib/required下的jar包到sh web工程的WEB-INF/lib
下载mysql驱动mysql-connector-java-5.1.40-bin.jar
commons-dbcp2-2.1.1.jar
commons-pool2-2.4.2.jar
放入WEB/lib
创建持久层实体
创建包sh.pojo存放持久层的实体
创建实体Person,映射表person
package sh.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="person")
public class Person {
private long id;
private String name;
private int age;
@Id
@GeneratedValue
@Column(name="id")
public long getId(){
return id;
}
public void setId(long id){
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
编辑hibernate配置##
在WEB-INF下新建hibernate-cfg.xml
其中current_session_context_class设置为thread,是保证能从当前线程中获取到事务会话的方式。
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.pool_size">1</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<property name="show_sql">true</property>
<mapping class="sh.pojo.Person" />
</session-factory>
</hibernate-configuration>
创建数据库访问层实体
创建包sh.dao
创建java接口PersonDAO
package sh.dao;
import java.util.List;
import sh.pojo.Person;
public interface PersonDAO {
public List<Person> getAll();
public void add(Person person);
}
创建DAO实现PersonDAOImpl
在实现里由方法自己实现事务控制
package sh.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import sh.pojo.Person;
public class PersonDAOImpl implements PersonDAO {
@Autowrired
private SessionFactory sessionFactory;
@Override
public List<Person> getAll() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List<Person> all = null;
try{
all = session.createQuery("from Person").getResultList();
}catch(HibernateException e){
session.getTransaction().rollback();
}
session.getTransaction().commit();
return all;
}
@Override
public void add(Person person) {
Session session = sessionFactory.getCurrentSession();
try{
session.beginTransaction();
session.save(person);
}catch(HibernateException e){
session.getTransaction().rollback();
}
session.getTransaction().commit();
}
}
编辑spring配置
编辑sh工程下的springmvc-servlet.xml:
- 添加数据源
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
- 配置会话工厂
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/hibernate-cfg.xml" />
</bean>
- 配置事务管理器
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
- 配置DAO
<bean id="personDAO" class="sh.dao.PersonDAOImpl">
</bean>
修改controller
在sh.controller中找到HelloController类中添加
@Autowired
PersonDAO personDAO;
并将addPerson和getAllPerson改为如下:
@RequestMapping(value = "/person", method = RequestMethod.POST)
public @ResponseBody
Person addPerson(@RequestBody Person person) {
sh.pojo.Person p = new sh.pojo.Person();
p.setAge(person.getAge());
p.setName(person.getName());
personDAO.add(p);
return person;
}
@RequestMapping(value = "/person", method = RequestMethod.GET)
public @ResponseBody
List<Person> getAllPerson() {
List<sh.pojo.Person> list = personDAO.getAll();
List<Person> list2= new ArrayList<Person>();
if(list!=null){
for(sh.pojo.Person p:list){
Person p2 = new Person();
p2.setAge(p.getAge());
p2.setName(p.getName());
list2.add(p2);
}
}
return list2;
}
测试
利用postman发送post请求
这里写图片描述在浏览器中访问并查看返回结果
这里写图片描述
网友评论