以添加员工为例,实现Spring、SpringMVC和Hibernate简单整合
1.创建数据库和表
CREATE DATABASE `employee` CREATE TABLE `employee`.`employee`( `id` INT(11) NOT NULL AUTO_INCREMENT , `name` VARCHAR(11) , PRIMARY KEY (`id`) );
2.导入jar包
//将项目需要的所有的jar包提前导入到项目中
3.创建项目所有的包
3.1.1 pojo类 Employee
public class Employee{ private Integer id; private String name; //省略set/get方法 }
3.1.2 pojo类的映射文件 Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.itqf.pojo.Employee" table="employee"> <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> </class> </hibernate-mapping>
3.2 dao层 (通常一个dao类对应一张表的增删改查)
//dao层对象继承HibernateDaoSupport 通过gethibernateTemplate()操作数据库 public class EmployeeDao extends HibernateDaoSupport{ //对数据库进行insert操作 public void addEmployee(Employee employee){ getHibernateTemplate().save(employee); } }
3.3 service层(service层处理业务逻辑)
@Service//通过注解创建service层的bean public class EmployeeService { @Autowired//注解注入 private EmployeeDao employeeDao; //调用dao层添加 public void addEmployee(Employee employee){ employeeDao.addEmployee(employee); } }
3.4 controller层(控制器层)
@Controller//控制器注解 配置文件通过扫描这个注解 public class EmployeeController { @Autowired//注解注入 private EmployeeService employeeService; @RequestMapping("/addEmployee.html")//映射路径 //自动映射成pojo类,前提:表单属性的name值必须和pojo类的属性名一致,必须有无参的构造方法 public String addEmployee(Employee employee){ employeeService.addEmployee(employee); return "/index.jsp"; } }
4.配置文件处理
4.1 web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!--监听项目启动 自动加载applicationContext.xml--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置前端控制器 默认加载springmvc-servlet.xml(前提:该配置文件在WEB-INF下) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <!-- 映射路径 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <!--编码格式--> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
4.2 数据库连接的属性文件 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/employee?characterEncoding=utf-8 jdbc.username=root jdbc.password=111
4.3 applicationContext.xml
Spring的配置文件:
负责管理bean类
负责管理数据源(数据库连接信息等)
负责管理事务(声明式事务)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd "> <!--扫描数据库连接信息 该配置文件包含了数据库连接需要的信息--> <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" system-properties-mode="NEVER"/> <!--配置数据源--> <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="password" value="${password}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="driverClassName" value="${driver}"/> </bean> <!--配置sessionFactory--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="ds"/> <!--在spring中配置hibernate属性--> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/itqf/pojo/Employee.hbm.xml</value> </list> </property> </bean> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!--配置通知类--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" rollback-for="Exception"/> </tx:attributes> </tx:advice> <!--定义事务切面--> <aop:config> <aop:pointcut id="serviceMethod" expression="execution(* com.itqf.service..*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/> </aop:config> <!--扫描service注解,自动创建bean--> <context:component-scan base-package="com.itqf.service"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <!-- 配置 dao层对象 并注入sessionFactory对象--> <bean id="deptDao" class="com.itqf.dao.DeptDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="employeeDao" class="com.itqf.dao.EmployeeDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans>
4.3 SpringMVC的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd "> <!--默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter--> <mvc:annotation-driven/> <!-- 扫描控制器注解 --> <context:component-scan base-package="com.itqf.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
5.页面设置(员工id为主键,设置了自动增长,这里可以省略)
<html> <head> <title>Title</title> </head> <body> <form action="/addEmployee.html" method="post">员工姓名:<input type="text" name="name"/><br> <input type="submit" value="添加" />${massage} </form> </body> </html>