Spring+Spring+Hibernate 框架搭建
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring+Spring+Hibernate 框架搭建相关的知识,希望对你有一定的参考价值。
一、项目结构及所需jar包
1.1项目结构
1.2依赖jar包(含json-lib及 log4j)
二、配置文件
2.1、web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SSH</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 加载所有的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:com/lcy/ssh/config/spring-*.xml</param-value> </context-param> <!-- 配置Spring监听 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:com/lcy/ssh/config/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2.2、springmvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <context:component-scan base-package="com.lcy.ssh.controller" /> <mvc:annotation-driven > <!-- 消息转换器 --> <!-- 解决@ResponseBody中文乱码 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
2.3、spring-common.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://数据库IP/test" /> <property name="username" value="用户名" /> <property name="password" value="密码" /> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="annotatedClasses"> <list> <value>com.lcy.ssh.pojo.User</value> <value>com.lcy.ssh.pojo.Type</value> </list> </property> </bean> <!-- 配置一个事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置事务,使用代理的方式 --> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop> <prop key="del*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> </beans>
2.4、spring-beans.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDAOImpl" class="com.lcy.ssh.dao.impl.UserDaoImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="userServiceBase" class="com.lcy.ssh.service.impl.UserServiceImpl"> <property name="userDao" ref="userDAOImpl" /> </bean> <bean name="userService" parent="transactionProxy"> <property name="target" ref="userServiceBase" /> </bean> <bean id="typeDAOImpl" class="com.lcy.ssh.dao.impl.TypeDaoImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="typeServiceBase" class="com.lcy.ssh.service.impl.TypeServiceImpl"> <property name="typeDao" ref="typeDAOImpl" /> </bean> <bean name="typeService" parent="transactionProxy"> <property name="target" ref="typeServiceBase" /> </bean> </beans>
2.5、log4j.properties配置
### set log levels ### log4j.rootLogger = debug,stdout,D,E log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =D://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
三、代码实现
3.1、代码结构
3.2、pojo
3.2.1、Type.java
package com.lcy.ssh.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.CascadeType; import org.hibernate.annotations.ForeignKey; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "type") public class Type { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") private String id; @Column(nullable = false, length = 32) private String name; @ManyToOne @JoinColumn(name = "userID") private User user; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
3.2.2、User.java
package com.lcy.ssh.pojo; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") @Column(length = 32) private String id; @Column(nullable = false, length = 32) private String name; @Column(nullable = false) private int age; @OneToMany(fetch=FetchType.EAGER) @OrderBy("id ASC") private Set<Type> types=new HashSet<Type>(); public String getId() { return id; } public void setId(String id) { this.id = id; } 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 Set<Type> getTypes() { return types; } public void setTypes(Set<Type> types) { this.types = types; } }
3.3、dao
3.3.1、TypeDao.java
package com.lcy.ssh.dao; import java.util.List; import com.lcy.ssh.pojo.Type; public interface TypeDao { public void addType(Type type) throws Exception; public List<Type> getTypes() throws Exception; }
3.3.2、UserDao.java
package com.lcy.ssh.dao; import java.util.List; import com.lcy.ssh.pojo.User; public interface UserDao{ public void addUser(User user) throws Exception; public List<User> getUsers() throws Exception; public User findUserById(String id) throws Exception; }
3.4、dao.impl
3.4.1、TypeDaoImpl.java
package com.lcy.ssh.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import com.lcy.ssh.dao.TypeDao; import com.lcy.ssh.pojo.Type; public class TypeDaoImpl implements TypeDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void addType(Type type) throws Exception { sessionFactory.getCurrentSession().save(type); } @Override public List<Type> getTypes() throws Exception { String hql="from Type"; Query query=sessionFactory.getCurrentSession().createQuery(hql); return query.list(); } }
3.4.2、UserDaoImpl.java
package com.lcy.ssh.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import com.lcy.ssh.dao.UserDao; import com.lcy.ssh.pojo.User; public class UserDaoImpl implements UserDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void addUser(User user) throws Exception { sessionFactory.getCurrentSession().save(user); } public List<User> getUsers() throws Exception { String hql="from User"; Query query=sessionFactory.getCurrentSession().createQuery(hql); return query.list(); } public User findUserById(String id) throws Exception { String hql="from User where id=?"; Query query=sessionFactory.getCurrentSession().createQuery(hql); query.setString(0, id); User user=(User) query.list().get(0); return user; } }
3.5、service
3.5.1、TypeService.java
package com.lcy.ssh.service; import java.util.List; import com.lcy.ssh.pojo.Type; public interface TypeService { public void addType(Type type) throws Exception; public List<Type> getTypes() throws Exception; }
3.5.2、UserService.java
package com.lcy.ssh.service; import java.util.List; import com.lcy.ssh.pojo.User; public interface UserService { public void addUser(User user) throws Exception; public List<User> getUsers() throws Exception; public User findUserById(String id) throws Exception; }
3.6、service.impl
3.6.1、TypeServiceImpl.java
package com.lcy.ssh.service.impl; import java.util.List; import com.lcy.ssh.dao.TypeDao; import com.lcy.ssh.pojo.Type; import com.lcy.ssh.service.TypeService; public class TypeServiceImpl implements TypeService{ private TypeDao typeDao; public void setTypeDao(TypeDao typeDao) { this.typeDao = typeDao; } public void addType(Type type) throws Exception { typeDao.addType(type); } @Override public List<Type> getTypes() throws Exception { return typeDao.getTypes(); } }
3.6.2、UserServiceImpl.java
package com.lcy.ssh.service.impl; import java.util.List; import com.lcy.ssh.dao.UserDao; import com.lcy.ssh.pojo.User; import com.lcy.ssh.service.UserService; public class UserServiceImpl implements UserService { private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void addUser(User user) throws Exception { userDao.addUser(user); } public List<User> getUsers() throws Exception { return userDao.getUsers(); } public User findUserById(String id) throws Exception { return userDao.findUserById(id); } }
3.7、controller
3.7.1、TypeController.java
package com.lcy.ssh.controller; import java.util.List; import javax.annotation.Resource; import net.sf.json.JSONArray; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.lcy.ssh.pojo.Type; import com.lcy.ssh.pojo.User; import com.lcy.ssh.service.TypeService; import com.lcy.ssh.service.UserService; @Controller public class TypeController { @Resource(name = "typeService") private TypeService typeService; @Resource(name="userService") private UserService userService; @RequestMapping("/addType") @ResponseBody public void addType() throws Exception { Type type = new Type(); type.setName("学生"); User user=userService.findUserById("297e02335e416f9b015e4170e0130000"); type.setUser(user); typeService.addType(type); } @RequestMapping("/getTypesJson") @ResponseBody public String getTypesJson() throws Exception { List<Type> list=typeService.getTypes(); JSONArray jsonArray=JSONArray.fromObject(list); return jsonArray.toString(); } }
3.7.2、UserController.java
package com.lcy.ssh.controller; import java.util.List; import javax.annotation.Resource; import net.sf.json.JSONArray; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.lcy.ssh.pojo.User; import com.lcy.ssh.service.UserService; @Controller public class UserController { @Resource(name="userService") private UserService userService; @RequestMapping("/addUser") @ResponseBody public void addUser() throws Exception { User user=new User(); user.setName("梁城月"); user.setAge(22); userService.addUser(user); } @RequestMapping("/getUsersJson") @ResponseBody public String getUsersJson() throws Exception { List<User> users=userService.getUsers(); System.out.println(); JSONArray jsonArray=JSONArray.fromObject(users); return jsonArray.toString(); } }
以上是关于Spring+Spring+Hibernate 框架搭建的主要内容,如果未能解决你的问题,请参考以下文章
使用 Hibernate + Spring 进行缓存 - 一些问题
java中的struts2+spring+Hibernate整合的框架中如何使用Ajax完成用户注册的用户名重复