spring+springmvc+ibatis整合注解方式实例

合集下载

SpringMVC+Spring+Hibernate框架整合原理,作用及使用方法

SpringMVC+Spring+Hibernate框架整合原理,作用及使用方法

SpringMVC+Spring+Hibernate框架整合原理,作⽤及使⽤⽅法SSM框架是spring MVC ,spring和mybatis框架的整合,是标准的MVC模式,将整个系统划分为表现层,controller层,service层,DAO层四层使⽤spring MVC负责请求的转发和视图管理spring实现业务对象管理,mybatis作为数据对象的持久化引擎原理:SpringMVC:1.客户端发送请求到DispacherServlet(分发器)2.由DispacherServlet控制器查询HanderMapping,找到处理请求的Controller3.Controller调⽤业务逻辑处理后,返回ModelAndView4.DispacherSerclet查询视图解析器,找到ModelAndView指定的视图5.视图负责将结果显⽰到客户端Spring:我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们中的类,当然也包括service dao⾥⾯的),有了这个机制,我们就不⽤在每次使⽤这个类的时候为它初始化,很少看到关键字new。

另外spring的aop,事务管理等等都是我们经常⽤到的。

Mybatis:mybatis是对jdbc的封装,它让数据库底层操作变的透明。

mybatis的操作都是围绕⼀个sqlSessionFactory实例展开的。

mybatis通过配置⽂件关联到各实体类的Mapper⽂件,Mapper⽂件中配置了每个类对数据库所需进⾏的sql语句映射。

在每次与数据库交互时,通过sqlSessionFactory拿到⼀个sqlSession,再执⾏sql命令。

使⽤⽅法:要完成⼀个功能:1. 先写实体类entity,定义对象的属性,(可以参照数据库中表的字段来设置,数据库的设计应该在所有编码开始之前)。

2. 写Mapper.xml(Mybatis),其中定义你的功能,对应要对数据库进⾏的那些操作,⽐如 insert、selectAll、selectByKey、delete、update等。

springmvc+spring+mybatis整合

springmvc+spring+mybatis整合

springmvc+spring+mybatis整合首先在整合这个框架的时候,想想其一般的步骤是怎样的,先有个步骤之后,不至于在后面的搞混了,这样在整合的时候也比较清晰些。

然后我们就细细的一步一步来整合。

1 创建一个Web项目。

2 导入Mybatis3、Spring4、SpringMVC4、连接数据库(我使用的数据库是mysql)的jar包。

我所用的包:spring-websocket-4.2.0.RELEASE.jar3 创建Mybatis3、Spring4、SpringMVC4、连接数据库的配置文件。

4 配置web.xml1<?xml version="1.0" encoding="UTF-8"?>2<web-app version="2.5"3xmlns="/xml/ns/javaee"4xmlns:xsi="/2001/XMLSchema-instance" 5xsi:schemaLocation="/xml/ns/javaee6/xml/ns/javaee/web-app_2_5.xsd">78<!-- 告知javaEE容器,有哪些内容需要添加到上下文中去--> 9<context-param>10<param-name>contextConfigLocation</param-name> 11<param-value>12/WEB-INF/classes/applicationContext.xml,13<!-- /WEB-INF/classes/mvc-servlet.xml -->14</param-value>15</context-param>161718<!-- 加载LOG4J -->19<context-param>20<param-name>log4jConfigLocation</param-name> 21<param-value>/WEB-INF/log4j.xml</param-value>22</context-param>2324<context-param>25<param-name>log4jRefreshInterval</param-name> 26<param-value>60000</param-value>27</context-param>2829<!-- 动态设置项目的运行路径-->30<context-param>31<param-name>webAppRootKey</param-name>32<param-value>ssm.root</param-value>33</context-param>3435<!-- 配置静态资源-->36<servlet-mapping>37<servlet-name>default</servlet-name>38<url-pattern>/static/*</url-pattern>39</servlet-mapping>404142<!-- 配置springmvc的前端控制器-->43<servlet>44<servlet-name>mvc</servlet-name>45<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>46<!-- 默认情况下:DispatcherServlet会寻找WEB-INF下,命名规范为[servlet-name]-servlet.xml文件。

Spring和MyBatis整合(注解版)

Spring和MyBatis整合(注解版)

Spring和MyBatis整合(注解版)1.导⼊所需要的依赖<!--MyBatis和Spring的整合包由MyBatis提供--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><!--MyBatis的核⼼jar⽂件--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency>View Code2.entity实体类3.dao层接⼝4.service接⼝5.serviceimpl实现类6.Dao.xml配置7.jdbc.properties配置8.applicationContext.xml⼤配置⽂件<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xmlns:context="/schema/context" xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/aop/schema/aop/spring-aop.xsd /schema/context /schema/context/spring-context.xsd /schema/tx http://www.springf <context:component-scan base-package="com.spring"/><!-- 配置数据源 spring内置的数据源--><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${ername}"></property><property name="password" value="${jdbc.password}"></property></bean><!-- 引⼊属性⽂件 --><context:property-placeholder location="jdbc.properties.properties"/><!-- &lt;!&ndash;注册DAO层:mapper的代理对象&ndash;&gt;<bean id="personDao"class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="mapperInterface" value="com.spring.dao.PersonDao"></property><property name="sqlSessionFactory"ref="sqlSessionFactory"></property></bean>&lt;!&ndash;配置service层对象&ndash;&gt;<bean id="personService"class="com.spring.service.PersonServiceImpl"><property name="dao"ref="personDao"></property></bean>--><!-- sqlSessionFactory 创建SqlSession对象的⼯⼚ --><bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource"ref="dataSource"></property><!-- Mybatis的⼤配置⽂件 --><property name="typeAliasesPackage" value="com.spring.entity"></property><!-- 扫描sql配置⽂件:mapper需要的xml⽂件 --><property name="mapperLocations" value="classpath*:mapper/*.xml"/></bean><!-- MapperScannerConfigurer 扫描mapper⽂件扫描器 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.spring.dao"></property></bean><!-- transactionManager 事务管理器--><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource"ref="dataSource"></property></bean><!-- 事务通知--><tx:advice transaction-manager="transactionManager" id="txAdvice"><tx:attributes><!--get系列⽅法设置事务的隔离级别和传播⾏为--><tx:method name="get*" isolation="READ_COMMITTED" propagation="REQUIRED"/></tx:attributes></tx:advice></beans>View Code9.测试类结果:。

spring+springmvc+mybatis组合总结

spring+springmvc+mybatis组合总结

spring+springmvc+mybatis组合总结springmvc+spring+mybatis整合:1. 拷贝所需jar2. 创建spring配置⽂件(beans.xml)3. 配置数据源<bean id="dataSource" class="mons.dbcp.BasicDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property><property name="username" value="root"></property><property name="password" value=""></property></bean>4.创建SqlSessionFactory实例:<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 指定数据源 --><property name="dataSource" ref="dataSource"/><!-- 指定mybatis的配置⽂件 --><property name="configLocation" value="classpath:mybatis-config.xml"/></bean><!--映射接⼝扫描mapper包下的所有xml⽂件 mapper是个包名应该是在main测试的时候才使⽤--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.liu.mapper"></property></bean>5. 配置事务<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean>6. 配置事务的传播特性<tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="find*" read-only="true"/><tx:method name="get*" read-only="true"/><tx:method name="query*" read-only="true"/><tx:method name="add*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="del*" propagation="REQUIRED"/></tx:attributes></tx:advice>7. 配置AOP<!-- 配置AOP --><aop:config><!--配置切⾯必须要有空格 *空格 ssmy 否则会报错--><aop:config><aop:pointcut expression="execcution(*空格 ssmy.service.impl.*.*(..))" id="pointcut"/><aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"/></aop:config>9. 配置DispatcherServlet<!-- 配置Spring核⼼控制器 --><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>*.do</url-pattern></servlet-mapping>10. 创建springmvc-servlet.xml配置⽂件:<!-- 注解扫描器 --><context:component-scan base-package="com.liu"/><!-- 配置试图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean><import resource="classpath:beans.xml"/>。

spring+spring mvc+mybits框架整合

spring+spring mvc+mybits框架整合

主要介绍三大框架的整合,至于环境的搭建以及项目的创建可以参考其他资料。

这次整合主要用到两个配置文件:spring-mybatis.xm,包含spring和mybatis的配置文件,还有个是spring-mvc.xml的配置文件,此外有两个资源文件:jdbc.propertis和log4j.properties。

完整的目录结构如下图:本框架中用到的所有jar包都在源码中。

本测试项目中用到的是sqlserver数据库,MyEclipse 8.6和apache-tomcat-7.0.41下来逐一介绍配置文件:1、spring-mybatis.xml这个文件就是用来完成spring和mybatis的整合的。

这里面也没多少行配置,主要的就是自动扫描,自动注入,配置数据库,注释也很详细<?xml version="1.0"encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.1.xsd/schema/context/schema/context/spring-context-3.1.xsd/schema/mvc/schema/mvc/spring-mvc-4.0.xsd"><!-- 自动扫描 --><context:component-scan base-package="com.myProcess.study"/><!-- 引入配置文件 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"value="classpath:jdbc.properties"/> </bean><bean id="dataSource"class="mons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName"value="${driver}"/><property name="url"value="${url}"/><property name="username"value="${username}"/><property name="password"value="${password}"/><!-- 初始化连接大小 --><property name="initialSize"value="${initialSize}"></property><!-- 连接池最大数量 --><property name="maxActive"value="${maxActive}"></property><!-- 连接池最大空闲 --><property name="maxIdle"value="${maxIdle}"></property><!-- 连接池最小空闲 --><property name="minIdle"value="${minIdle}"></property><!-- 获取连接最大等待时间 --><property name="maxWait"value="${maxWait}"></property></bean><!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --><bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource"ref="dataSource"/><!-- 自动扫描mapping.xml文件 --><property name="mapperLocations"value="classpath:com/myProcess/study/mapping/*.xml"></property></bean><!-- DAO接口所在包名,Spring会自动查找其下的类 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage"value=".hnust.dao"/><property name="sqlSessionFactoryBeanName"value="sqlSessionFactory"></property></bean><!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"ref="dataSource"/></bean></beans>2、log4j.propertieslog4j.rootLogger=INFO,Console,File#定义日志输出目的地为控制台log4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.Target=System.out#可以灵活地指定日志输出格式,下面一行是指定具体的格式yout = org.apache.log4j.PatternLayoutyout.ConversionPattern=[%c]-%m%n#文件大小到达指定尺寸的时候产生一个新的文件log4j.appender.File = org.apache.log4j.RollingFileAppender#指定输出目录log4j.appender.File.File = logs/ssm.log#定义文件最大大小log4j.appender.File.MaxFileSize = 10MB# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志log4j.appender.File.Threshold = ALLyout = org.apache.log4j.PatternLayoutyout.ConversionPattern =[%p][%d{yyyy-MM-ddHH\:mm\:ss}][%c]%m%n3、spring-mvc.xml主要是自动扫描控制器,视图模式,注解的启动这三个<?xml version="1.0"encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.1.xsd/schema/context/schema/context/spring-context-3.1.xsd/schema/mvc/schema/mvc/spring-mvc-4.0.xsd"><!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --><context:component-scan base-package="com.myProcess.study.web"/><!--避免IE执行AJAX时,返回JSON出现下载文件 --><bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConvert er"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value></list></property></bean><!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAd apter"><property name="messageConverters"><list><ref bean="mappingJacksonHttpMessageConverter"/><!-- JSON转换器 --></list></property></bean><!-- 定义跳转的文件的前后缀,视图模式配置--><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个可用的url地址 --><property name="prefix"value="/WEB-INF/jsp/"/><property name="suffix"value=".jsp"/></bean><!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --><bean id="multipartResolver"class="monsMultipartResolver"> <!-- 默认编码 --><property name="defaultEncoding"value="utf-8"/><!-- 文件大小最大值 --><property name="maxUploadSize"value="10485760000"/><!-- 内存中的最大值 --><property name="maxInMemorySize"value="40960"/></bean></beans>4、web.xml这里面对spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前2框架整合不需要在此处进行任何配置。

spring与ibatis框架整合

spring与ibatis框架整合

spring与ibatis框架整合问题:spring与ibatis框架整合回答:Spring和Ibatis框架整合的思路与spring和hibernate框架的整合思路基本一致。

步骤一:新建立一个项目。

步骤二:为该项目添加spring的应用环境。

步骤三:导入Ibatis的必须JAR包以及数据库JAR包。

步骤四:新建实体Bean。

如下:package cn.test.entity;import java.io.Serializable;/*** @author Administrator**学生实体Bean**/public class Student implements Serializable/****/private static final long serialVersionUID = 1L; private Integer id;private String studentname;private Integer studentage;private String studentaddress;public Integer getId()return id;public void setId(Integer id)this.id = id;public String getStudentname()return studentname;public void setStudentname(String studentname) this.studentname = studentname;public Integer getStudentage()return studentage;public void setStudentage(Integer studentage) this.studentage = studentage;public String getStudentaddress()return studentaddress;public void setStudentaddress(String studentaddress)this.studentaddress = studentaddress;步骤五:新建相应的Bean的配置文件。

spring mvc注解实例

spring mvc注解实例

本文主要介绍使用注解方式配置的spring mvc,包括数据访问层的实现web.xml配置:<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance" xmlns="http:// /xml/ns/javaee" xmlns:web="/xml/ns/javaee/web-ap p_2_5.xsd" xsi:schemaLocation="/xml/ns/javaee http://java.su /xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><display-name>s3h3</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</l istener-class></listener><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servle t-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring</servlet-name> <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller --><url-pattern>*.do</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>spring-servlet,主要配置controller的信息<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="http:// /schema/p"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans http://www. /schema/beans/spring-beans-3.0.xsd/schema/aop http://www.springframework.o rg/schema/aop/spring-aop-3.0.xsd/schema/tx http://www.springframework.or g/schema/tx/spring-tx-3.0.xsd/schema/context http://www.springframewo /schema/context/spring-context-3.0.xsd"><context:annotation-config /><!-- 把标记了@Controller注解的类转换为bean --><context:component-scan base-package="com.mvc.controller"/> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationM ethodHandlerAdapter"/><!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --><bean class="org.springframework.web.servlet.view.InternalResourceView Resolver"p:prefix="/WEB-INF/view/" p:suffix=".jsp"/><bean id="multipartResolver"class="monsMultipartRe solver"p:defaultEncoding="utf-8"/></beans>applicationContext.xml代码<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:aop="/schema/aop" xmlns:context="http:// /schema/context"xmlns:p="/schema/p" xmlns:tx="http://www.sprin /schema/tx"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans http://www.springframewo /schema/beans/spring-beans-3.0.xsd/schema/context http://www.springframework.o rg/schema/context/spring-context-3.0.xsd/schema/aop /s chema/aop/spring-aop-3.0.xsd/schema/tx /sc hema/tx/spring-tx-3.0.xsd"><context:annotation-config /><context:component-scan base-package="com.mvc"/><!-- 自动扫描所有注解该路径 --><context:property-placeholder location="classpath:/hibernate.properties "/><bean id="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFacto ryBean"><property name="dataSource" ref="dataSource"/><property name="hibernateProperties"><props><prop key="hibernate.dialect">${dataSource.dialect}</prop><prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><property name="packagesToScan"><list><value>com.mvc.entity</value><!-- 扫描实体类,也就是平时所说的model --></list></property></bean><bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/><property name="dataSource" ref="dataSource"/></bean><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${dataSource.driverClassName} "/><property name="url" value="${dataSource.url}"/><property name="username" value="${ername}"/><property name="password" value="${dataSource.password}"/></bean><!-- Dao的实现 --><bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"><property name="sessionFactory" ref="sessionFactory"/></bean><tx:annotation-driven transaction-manager="transactionManager"/><tx:annotation-driven mode="aspectj"/><aop:aspectj-autoproxy/></beans>hibernate.properties数据库连接配置dataSource.password=123ername=rootdataSource.databaseName=testdataSource.driverClassName=com.mysql.jdbc.DriverdataSource.dialect=org.hibernate.dialect.MySQL5DialectdataSource.serverName=localhost:3306dataSource.url=jdbc:mysql://localhost:3306/testdataSource.properties=user=${ername};databaseName=${dataSource.d atabaseName};serverName=${dataSource.serverName};password=${dataSource.passwor d}dataSource.hbm2ddl.auto=update配置已经完成,下面开始例子先在数据库建表,例子用的是mysql数据库CREATE TABLE `test`.`student` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL,`psw` varchar(45) NOT NULL,PRIMARY KEY (`id`))建好表后,生成实体类package com.mvc.entity;import java.io.Serializable;import javax.persistence.Basic;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name = "student")public class Student implements Serializable {private static final long serialVersionUID = 1L;@Id@Basic(optional = false)@GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false)private Integer id;@Column(name = "name")private String user;@Column(name = "psw")private String psw;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUser() {return user;}public void setUser(String user) {er = user;}public String getPsw() {return psw;}public void setPsw(String psw) {this.psw = psw;}}Dao层实现package com.mvc.dao;import java.util.List;public interface EntityDao {public List<Object> createQuery(final String queryString);public Object save(final Object model);public void update(final Object model);public void delete(final Object model);}package com.mvc.dao;import java.util.List;import org.hibernate.Query;import org.springframework.orm.hibernate3.HibernateCallback;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao {public List<Object> createQuery(final String queryString) { return (List<Object>) getHibernateTemplate().execute(new HibernateCallback<Object>() {public Object doInHibernate(org.hibernate.Session sessio n)throws org.hibernate.HibernateException {Query query = session.createQuery(queryString);List<Object> rows = query.list();return rows;}});}public Object save(final Object model) {return getHibernateTemplate().execute(new HibernateCallback<Object>() {public Object doInHibernate(org.hibernate.Session sessio n)throws org.hibernate.HibernateException {session.save(model);return null;}});}public void update(final Object model) {getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session)throws org.hibernate.HibernateException {session.update(model);return null;}});}public void delete(final Object model) {getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session)throws org.hibernate.HibernateException {session.delete(model);return null;}});}}Dao在applicationContext.xml注入<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"><property name="sessionFactory" ref="sessionFactory"/></bean>Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。

SpringBoot整合mybatis使用注解实现动态Sql、参数传递等常用操作(实现方法)

SpringBoot整合mybatis使用注解实现动态Sql、参数传递等常用操作(实现方法)

SpringBoot整合mybatis使⽤注解实现动态Sql、参数传递等常⽤操作(实现⽅法)前⾯介绍了Spring Boot 整合mybatis 使⽤注解的⽅式实现数据库操作,介绍了如何⾃动⽣成注解版的mapper 和pojo类。

接下来介绍使⽤mybatis 常⽤注解以及如何传参数等数据库操作中的常⽤操作。

其实,mybatis 注解⽅式和 XML配置⽅式两者的使⽤基本上相同,只有在构建 SQL 脚本有所区别,所以这⾥重点介绍两者之间的差异,以及增删改查,参数传递等注解的常⽤操作。

注解介绍mybatis 注解⽅式的最⼤特点就是取消了Mapper的XML配置,具体的 SQL 脚本直接写在 Mapper 类或是 SQLProvider 中的⽅法动态⽣成。

mybatis 提供的常⽤注解有:@Insert 、@Update 、@Select、 @Delete等标签,这些注解其实就是 MyBatis 提供的来取代其XML配置⽂件的。

1、@Select 注解@Select,主要在查询的时候使⽤,查询类的注解,⼀般简单的查询可以使⽤这个注解。

@Select({"select","id, company_id, username, password, nickname, age, sex, job, face_image, province, ","city, district, address, auth_salt, last_login_ip, last_login_time, is_delete, ","regist_time","from sys_user","where id = #{id,jdbcType=VARCHAR}"})@Results({@Result(column="id", property="id", jdbcType=JdbcType.VARCHAR, id=true),@Result(column="company_id", property="companyId", jdbcType=JdbcType.VARCHAR),@Result(column="face_image", property="faceImage", jdbcType=JdbcType.VARCHAR),@Result(column="auth_salt", property="authSalt", jdbcType=JdbcType.VARCHAR),@Result(column="last_login_ip", property="lastLoginIp", jdbcType=JdbcType.VARCHAR),@Result(column="last_login_time", property="lastLoginTime", jdbcType=JdbcType.TIMESTAMP),@Result(column="is_delete", property="isDelete", jdbcType=JdbcType.INTEGER),@Result(column="regist_time", property="registTime", jdbcType=JdbcType.TIMESTAMP)})User selectByPrimaryKey(String id);注意:如果是多个参数,需要将 #后⾯的参数和传⼊的变量名保持⼀致。

Spring整合MyBatis-纯注解形式(最简)

Spring整合MyBatis-纯注解形式(最简)

Spring整合MyBatis-纯注解形式(最简)Spring整合MyBatis-纯注解形式(最简)前提: 整合MyBatis使⽤Idea创建Maven⼯程, 下图为⼯程⽬录结构1. 导⼊Maven⼯程相关的坐标 - pom.xml<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.xxx</groupId><artifactId>spring-mybatis02-zh</artifactId><version>1.0</version><!--指定java1.8版本--><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><piler.source>1.8</piler.source><piler.target>1.8</piler.target></properties><dependencies><!--MyBatis坐标--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.3</version></dependency><!--Mybatis-spring整合坐标--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><!--druid连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><!--MySQL连接坐标--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><!--spring坐标--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.9.RELEASE</version></dependency><!--Spring-jdbc--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.9.RELEASE</version></dependency><!--Junit-单元测试坐标--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--Junit-spring的test--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.9.RELEASE</version></dependency></dependencies></project>View Code2. 创建jdbc的配置⽂件 - jdbc.propertiesjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/spring_dbername=rootjdbc.password=rootView Code3. config - SpringConfig.javapackage com.xxx.config;import ponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;import org.springframework.context.annotation.PropertySource;/*** @author : longChuanJiang* @date : Created in 2020/8/24 14:07*/@Configuration@ComponentScan(value = "com.xxx")@PropertySource("classpath:jdbc.properties")@Import({JdbcConfig.class, MyBatisConfig.class})public class SpringConfig {/*###########-Spring核⼼配置类详解-###########1. 开启Spring注解扫描器, 扫描Spring可识别的注解@ComponentScan(value = "com.xxx")2. 加载jdbc配置⽂件@PropertySource("classpath:jdbc.properties")3. 导⼊JdbcConfig和MyBatisConfig的配置类@Import({JdbcConfig.class, MyBatisConfig.class})*/}View Code4. config - JdbcConfig.javapackage com.xxx.config;import com.alibaba.druid.pool.DruidDataSource;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import javax.sql.DataSource;/*** @author : longChuanJiang* @date : Created in 2020/8/24 14:06*/public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${ername}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource getDataSource() {DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}}View Code5. config - MyBatisConfig.javapackage com.xxx.config;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import ponent;import javax.sql.DataSource;/*** @author : longChuanJiang* @date : Created in 2020/8/24 14:07*/public class MyBatisConfig {/*** 获取数据源** @param dataSource 数据源* @return数据源*/@Beanpublic SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource) { SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();ssfb.setDataSource(dataSource);// 设置实体类的别名路径ssfb.setTypeAliasesPackage("com.xxx.domain");return ssfb;}/*** 注册扫描器: 扫描包下⾯的mapper接⼝*/@Beanpublic MapperScannerConfigurer getMapperScannerConfigurer() {MapperScannerConfigurer msc = new MapperScannerConfigurer();// 设置MyBatis的Mapper接⼝路径msc.setBasePackage("com.xxx.dao");return msc;}}View Code6. dao - AccountDao.java(接⼝)package com.xxx.dao;import com.xxx.domain.Account;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import ponent;import java.util.List;/*** @author longChuanJiang*/@Componentpublic interface AccountDao {@Insert("insert into account(name,money)values(#{name},#{money})")void save(Account account);@Delete("delete from account where id = #{id} ")void delete(Integer id);@Update("update account set name = #{name} , money = #{money} where id = #{id} ") void update(Account account);@Select("select * from account")List<Account> findAll();@Select("select * from account where id = #{id} ")Account findById(Integer id);}View Code7. doamin - Account.javapackage com.xxx.domain;import java.io.Serializable;public class Account implements Serializable {private Integer id;private String name;private Double money;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}}View Code8. service - AccountService.java(接⼝)package com.xxx.service;import com.xxx.domain.Account;import java.util.List;public interface AccountService {void save(Account account);void delete(Integer id);void update(Account account);List<Account> findAll();Account findById(Integer id);}View Code9. service.impl - AccountServiceImpl.javapackage com.xxx.service.impl;import com.xxx.dao.AccountDao;import com.xxx.domain.Account;import com.xxx.service.AccountService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.stereotype.Service;import java.util.List;/*** @author longChuanJiang*/@Service("accountService")public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Overridepublic void save(Account account) {accountDao.save(account);}@Overridepublic void update(Account account) {accountDao.update(account);}@Overridepublic void delete(Integer id) {accountDao.delete(id);}@Overridepublic Account findById(Integer id) {return accountDao.findById(id);}@Overridepublic List<Account> findAll() {return accountDao.findAll();}}View Code10. 数据库源码 - spring-db.sql/*Navicat Premium Data TransferSource Server : localMySQLSource Server Type : MySQLSource Server Version : 50729Source Host : localhost:3306Source Schema : spring_dbTarget Server Type : MySQLTarget Server Version : 50729File Encoding : 65001Date: 24/08/2020 17:30:33*/SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS =0;-- ------------------------------ Table structure for account-- ----------------------------DROP TABLE IF EXISTS `account`;CREATE TABLE `account` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`money` double(255, 30) NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT =5CHARACTER SET= utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ------------------------------ Records of account-- ----------------------------INSERT INTO `account` VALUES (1, '张三', 24.990000000000000000000000000000);INSERT INTO `account` VALUES (2, '赵四', 26.120000000000000000000000000000);INSERT INTO `account` VALUES (3, '王五', 19555.555000000000000000000000000000);INSERT INTO `account` VALUES (4, 'jock', 193.222000000000000000000000000000);SET FOREIGN_KEY_CHECKS =1;View Code11. 测试源码 - AccountServiceTest.javapackage com.xxx.service;import com.xxx.config.SpringConfig;import com.xxx.domain.Account;import com.xxx.service.AccountService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List;/*** @author : longChuanJiang* @date : Created in 2020/8/24 14:43*/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfig.class)public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void findAllTest(){List<Account> all = accountService.findAll();System.out.println("all = " + all);}@Testpublic void findByIdTest(){Account ac = accountService.findById(4);System.out.println("ac = " + ac);}@Testpublic void saveTest(){Account account = new Account();account.setName("jock");account.setMoney(193.222);accountService.save(account);findAllTest();}}View Code。

Ibatis,Spring整合(注解方式注入)

Ibatis,Spring整合(注解方式注入)

Ibatis,Spring整合(注解⽅式注⼊)${原来姹紫嫣红开遍,似这般都付与扣钉⼋哥}<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:aop="/schema/aop" xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-2.5.xsd/schema/tx/schema/tx/spring-tx-2.5.xsd/schema/aop/schema/aop/spring-aop-2.5.xsd/schema/context/schema/context/spring-context-2.5.xsd"><!-- ⾃动扫描Bean --><context:component-scan base-package="com.tq365"/><!-- 强制使⽤CGLIB代理 --><aop:aspectj-autoproxy proxy-target-class="true"/><!-- DataSource数据源 --><bean id="dataSource" class="mons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property><property name="url"><value>jdbc:mysql://localhost:3306/ibatisorm</value></property><property name="username"><value>root</value></property><property name="password"><value>root</value></property></bean><!-- Spring iBatis SqlMapClient --><bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"><property name="configLocation" value="WEB-INF/sqlmap-config.xml"/><property name="dataSource" ref="dataSource"/></bean><!--事务管理DataSourceTransactionManager--><bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--启动spring注解功能--><tx:annotation-driven transaction-manager="txManager" /> <aop:config> <aop:pointcut id="baseServiceMethods" expression="execution(* com.tq365.samples.ibatis.dao.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="baseServiceMethods" /> </aop:config><aop:aspectj-autoproxy /> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="select*" read-only="true" propagation="REQUIRED" /> <tx:method name="find*" read-only="true" propagation="REQUIRED" /> <tx:methodname="save*" propagation="REQUIRED" isolation="REPEATABLE_READ" /> <tx:method name="update*" propagation="REQUIRED" isolation="REPEATABLE_READ" /> <!-- <tx:method name="add*" propagation="REQUIRED" isolation="REPEATABLE_READ" /> --> <tx:method name="delete*" propagation="REQUIRED" isolation="REPEATABLE_READ" /> </tx:attributes> </tx:advice></beans><?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMapConfig PUBLIC "-////DTD SQL Map Config 2.0//EN" "/dtd/sql-map-config-2.dtd"><sqlMapConfig><sqlMap resource="com/tq365/sqlMap/User.xml"/></sqlMapConfig>User.xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMap PUBLIC "-////DTD SQL Map 2.0//EN" "/dtd/sql-map-2.dtd"> <sqlMap namespace="User"><typeAlias alias="User" type="er"/><resultMap id="UserResult" class="User"><result property="id" column="id"/><result property="username" column="username"/><result property="address" column="address"/><result property="userpwd" column="userpwd"/></resultMap><insert id="addUser">insert user(username,userpwd,address)values(#username#,#userpwd#,#address#)</insert><select id="findUser" resultMap="UserResult">select * from user WHERE username=#username# and userpwd=#userpwd#</select><select id="findUserById" resultMap="UserResult">select * from user WHERE id=#id#</select><!-- User表内记录总条数 --><select id="getTotalCount" resultClass="int">select count(*) from user</select><select id="findAllPageUser" resultMap="UserResult">select * from user limit #start#,5</select></sqlMap>UserDAO.java接⼝package com.tq365.samples.ibatis.dao;import org.springframework.stereotype.Repository;import er;import com.tq365.sqmples.util.Pages;/*** UserDAO 接⼝*/@Repositorypublic interface UserDAO {/*** 通过ID查询* @param id* @return*/public User findUserById(int id);/*** 通过ID删除* @param id*/public void deleteUserById(int id);public void addUser(User user);/*** 查询指定的User对象* @param user* @return*/public User findUser(User user);/*** 通过⽤户名分页查询* @param username* @return*/public Pages<User> findUsersByUsername(String username,int pageNo);/*** 所有User对象分页* @param pageNo* @return*/public Pages<User> findAllPageUser(int pageNo);}BaseDao.javapackage com.tq365.samples.ibatis.dao;import javax.annotation.PostConstruct;import javax.annotation.Resource;import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;import com.ibatis.sqlmap.client.SqlMapClient;/*** BaseDao,Dao需继承此Dao* @author archie2010* since 2011-3-3 下午02:52:36*/public class BaseDao extends SqlMapClientDaoSupport{@Resource(name = "sqlMapClient")private SqlMapClient sqlMapClient;@PostConstructpublic void initSqlMapClient(){super.setSqlMapClient(sqlMapClient);}}@PostConstruct注解在⽅法上加上注解@PostConstruct,这个⽅法就会在Bean初始化之后被Spring容器执⾏(注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注⼊))。

SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)

SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)

SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)使用SSM(Spring、SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方。

之前没有记录SSM整合的过程,这次刚刚好基于自己的一个小项目重新搭建了一次,而且比项目搭建的要更好一些。

以前解决问题的过程和方法并没有及时记录,以后在自己的小项目中遇到我再整理分享一下。

这次,先说说三大框架整合过程。

个人认为使用框架并不是很难,关键要理解其思想,这对于我们提高编程水平很有帮助。

不过,如果用都不会,谈思想就变成纸上谈兵了!!!先技术,再思想。

实践出真知。

(可通过图片水印查看博客地址)1、基本概念1.1、SpringSpring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。

它是为了解决企业应用开发的复杂性而创建的。

Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。

然而,Spring的用途不仅限于服务器端的开发。

从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。

简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

1.2、SpringMVCSpring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。

Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

1.3、MyBatisMyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。

SpringBoot系列教程Mybatis+注解整合篇

SpringBoot系列教程Mybatis+注解整合篇
</dependencies>
<build> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </pluginManagement>
@Select("<script> select * from money " + "<trim prefix=\"WHERE\" prefixOverrides=\"AND | OR\">" + " <if test=\"id != null\">" + " id = #{id}" + " </if>" + " <if test=\"name != null\">" + " AND name=#{name}" + " </if>" + " <if test=\"money != null\">" + " AND money=#{money}" + " </if>" + "</trim>" + "</script>")

在spring中混合使用Hibernate和ibatis的配置方法

在spring中混合使用Hibernate和ibatis的配置方法

在spring中混合使用Hibernate和ibatis的配置方法Lee ⋅讨论在实际的项目开发中,如果只用hibernate,经常会遇到很多实现复杂的sql和map方法,这时候如果用ibatis却很简单,所以我们需要在一个项目中hibernate和ibatis并存,配置方法如下就可以实现来自:实现原理:Hibernate和ibatis在同一个webapp中混合使用在spring中的配置方法applicationContext-hibatis.xml文件的例子如下: ————————————————————————————————<!– Hibernate SessionFactory –><bean id=”sessionFactory”><property name=”dataSource”><ref bean=”dataSource”/></property><property name=”mappingResources”><list><value>org/javaresource/model/Role.hbm.xml</value><value>org/javaresource/model/User.hbm.xml</value><value>org/javaresource/model/UserCookie.hbm.xml</value><value>org/javaresource/model/UserRole.hbm.xml</value></list></property><property name=”hibernateProperties”><props><prop key=”hibernate.dialect”>@HIBERNATE-DIALECT@</prop></props></property></bean><!– SqlMap setup for iBATIS Database Layer –><bean id=”sqlMapClient”><property name=”configLocation”><value>classpath:/org/javaresource/persistence/ibatis/sql-map-config.xml</value></property></bean><!– Transaction manager for a single JDBC DataSource –><bean id=”transactionManager”><property name=”dataSource”><ref bean=”dataSource”/></property></bean><!– LookupDAO: iBatis implementation –><bean id=”lookupDAO”><pr operty name=”dataSource”><ref bean=”dataSource”/></property><property name=”sqlMapClient”><ref local=”sqlMapClient”/></property> </bean><!– UserDAO: Hibernate implementation –><bean id=”userDAO”><property name=”sessionFactory”><ref bean=”sessionFactory”/></property> </bean>。

SpringSpringMVCMyBatis整合

SpringSpringMVCMyBatis整合

SpringSpringMVCMyBatis整合今天主要想总结一下SSM的整合,之前已经将MyBatis和spring整合起来了,那么这次主要介绍怎样加入SpringMVC这个框架,在整合之前先简单介绍一下SpringMVC:SpringMVC是一种基于Java的,实现了”WEB MVC”设计模式,基于请求驱动类型的轻量级WEB框架,是Spring框架的重要组成部分,该框架使用了MVC架构模式的思想,将WEB层进行职责功能的解耦,基于请求驱动类型指的就是使用“请求-响应”模型,该框架的目的就是帮助我们简化web系统的开发。

SpringMVC中最重要的一个就是前端控制器:FontController:DispatcherServlet,MVC架构模式中要求一定要存在前端控制器,而且一定是由Servlet实现的,而Struts2严格来说称之为MVC的变种架构。

Servlet:Servlet规范对路径匹配规则是有要求的:1.如果一个路径是以/开头,以/*结尾,称之为路径前缀匹配2.如果一个路径是以*.开头,那么这个路径称之为扩展匹配3.其它所有的路径都是精确匹配SpringMVC架构模式:天生和Spring框架集成,能简单的进行Web层的单元测试。

搭建SpringMVC的开发环境:1.首先自然是要引入相关的Jar包,然后在web.xml中配置前端控制器:servlet当然由于我们现在创建的是WEB项目,记得在web.xml中配置一个全局的参数,在Tomcat 启动时就会去读取该文件:applicationContext.xml以下就是web.xml文件的具体配置内容:<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_3_0.xsd"><display-name>SpringMVCTest</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><filter><filter-name>encodingFilter</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><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter><!-- 解决put delete得不到数据的问题--><filter-name>HiddenHttpMethodFilter</filter-name><filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter><filter-mapping><filter-name>HiddenHttpMethodFilter</filter-name><servlet-name>springmvc</servlet-name></filter-mapping><!-- session超时定义,单位为分钟--><session-config><session-timeout>30</session-timeout></session-config><error-page><error-code>403</error-code><location>/WEB-INF/views/errors/403.jsp</location></error-page><error-page><error-code>404</error-code><location>/WEB-INF/views/errors/404.jsp</location></error-page><error-page><error-code>405</error-code><location>/WEB-INF/views/errors/405.jsp</location></error-page><error-page><error-code>500</error-code><location>/WEB-INF/views/errors/500.jsp</location></error-page></web-app>2.增加配置文件,默认DispatcherServlet会加载WEB-INF/[DispatcherServlet的Servlet名字]-servlet.xml配置文件,上面这样写就代表当前配置文件的名称为springmvc-servlet.xml,也就是配置文件的名称必须和Servlet的名字一样:“springmvc-servlet.xml”该配置文件中主要配置一些处理器映射器,处理适配器,视图解析器以及开启注解和扫描SpringMVC注解的包路径,以下就是具体配置内容:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xmlns:p="/schema/p"xmlns:aop="/schema/aop"xsi:schemaLocation="/schema/mvc/schema/mvc/spring-mvc-3.2.xsd/schema/beans/schema/beans/spring-beans-3.2.xsd/schema/context/schema/context/spring-context-3.2.xsd/schema/aop/schema/aop/spring-aop-3.2.xsd/schema/mvc/schema/mvc/spring-mvc-3.0.xsd"> <!-- 开启注解--><context:annotation-config /><!-- @Controller注解的使用前提配置--><mvc:annotation-driven /><!-- 扫描的包路径--><context:component-scan base-package="com.ecjtu.ssm"><context:exclude-filter type="annotation"expression="org.springframework.stereotype.Service" /></context:component-scan><mvc:interceptors><bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" /><bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"p:paramName="lang" /></mvc:interceptors><beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"> </bean><!-- request --><beanclass="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean> <!-- 将静态文件指定到某个特殊的文件夹中统一处理--><mvc:resources location="/resources/" mapping="/resources/**" /><!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理--><mvc:resources mapping="/images/**" location="/images/" /><mvc:resources mapping="/css/**" location="/css/" /><mvc:resources mapping="/others/**" location="/others/" /><mvc:resources mapping="/js/**" location="/js/" /><mvc:resources mapping="/html/**" location="/html/" /><!-- 文件上传--><bean id="multipartResolver"class="monsMultipartResolver"><property name="maxUploadSize" value="10000000" /><!-- 10M --></bean><!--注解映射器--><beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMappin g"/><!-- 添加对图片、字节、字符串、XML及json数据格式的支持,注意添加json支持的jar包--><bean id="messageAdapter"class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter "><property name="messageConverters"><list><beanclass="org.springframework.http.converter.StringHttpMessageConverter" /><beanclass="org.springframework.http.converter.FormHttpMessageConverter" /><beanclass="org.springframework.http.converter.ByteArrayHttpMessageConverter" /><beanclass="org.springframework.http.converter.xml.SourceHttpMessageConverter" /><beanclass="org.springframework.http.converter.BufferedImageHttpMessageConverter" /><beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> </list></property></bean><!--启动Spring MVC的注解功能,设置编码方式,防止乱码--><beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter "><property name="messageConverters"><list><beanclass="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value></list></property></bean></list></property></bean><!-- 定义JSP文件的位置--><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass"value="org.springframework.web.servlet.view.JstlView" /><property name="prefix" value="/WEB-INF/views/" /><property name="suffix" value=".jsp" /></bean></beans>这里我也一并将applicationContext.xml文件的内容都贴出来吧,里面都有详细的注释<?xml version="1.0" encoding="UTF-8"?>default-autowire="no" default-lazy-init="false"><!-- 配置Spring组件扫描的包路径--><context:component-scan base-package="com.ecjtu.ssm.*"><!-- 不包括@Controller注解--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /><context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /></context:component-scan><!-- 开启注解--><context:annotation-config /><!-- 读取外部的配置文件,这个配置文件主要配置了数据库的连接信息--><bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>classpath:db-config.properties</value></property></bean><!--本示例采用DBCP连接池,应预先添加DBCP包的依赖。

spring-mvc+mybatis注解方式事务管理

spring-mvc+mybatis注解方式事务管理

spring-mvc+mybatis注解⽅式事务管理配置⽂件:<!-- dataSource --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><property name="url" value="${db.master.url}" /><property name="username" value="${er}" /><property name="password" value="${db.master.password}" /><!-- 配置监控统计拦截的filters --><property name="filters" value="mergeStat,wall,log4j2" /><property name="initialSize" value="5" /><property name="maxActive" value="100" /><property name="minIdle" value="10" /><property name="maxWait" value="60000" /><property name="validationQuery" value="SELECT 'x'" /><property name="testOnBorrow" value="true" /><property name="testOnReturn" value="true" /><property name="testWhileIdle" value="true" /><property name="timeBetweenEvictionRunsMillis" value="60000" /><property name="minEvictableIdleTimeMillis" value="300000" /><property name="removeAbandoned" value="true" /><property name="removeAbandonedTimeout" value="1800" /><property name="logAbandoned" value="true" /></bean><!-- Spring整合Mybatis --><bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><!-- ⾃动扫描Mapping.xml⽂件 --><property name="mapperLocations" value="classpath*:/sqlMapperXml/*.xml"></property><property name="configLocation" value="classpath:xml/mybatis-config.xml"></property><property name="typeAliasesPackage" value="com.mingwork.model"/><property name="globalConfig" ref="globalConfig"/><property name="plugins"><array><!-- 分页插件配置 --><bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"><property name="dialectType" value="mysql"/><property name="optimizeType" value="aliDruid" /></bean></array></property></bean><!-- MP 全局配置 --><bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"><property name="idType" value="0"/><property name="dbColumnUnderline" value="true"/></bean><!-- MyBatis 动态实现 --><bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 对Dao 接⼝动态实现,需要知道接⼝在哪 --><property name="basePackage" value="com.mingwork.mapper"/></bean><!-- 事务管理 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 事务注解 --><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/><!-- 事务管理属性 --><tx:advice id="transactionAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="select*" propagation="REQUIRED" read-only="true" /><tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception" /><tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" /><tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception" /><tx:method name="*" propagation="REQUIRED" /></tx:attributes></tx:advice><!-- 配置切⾯ --><aop:config expose-proxy="true" proxy-target-class="true"><aop:advisor advice-ref="transactionAdvice" pointcut="execution(* com.mingwork.service..*.*(..))"/></aop:config>上⾯配置的意思就是配置⾯向切⾯,只要servcie中的⽅法抛出Exception,那么insert,update,delete的sql⽅法都会回滚。

SpringMVC3.0.5+Spring3.0.5+MyBatis3.0.4全注解实例详解三

SpringMVC3.0.5+Spring3.0.5+MyBatis3.0.4全注解实例详解三

Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解三2011-08-04 16:40:32 我来说两句 0我要投稿 [字体:小大]前两章我为大家详细介绍了如何搭建Maven环境、Spring MVC的流程结构、Spring MVC与Struts2的区别以及示例中的一些配置文件的分析。

在这一章,我就对示例的层次结构进行说明,以及MyBatis的一些简单介绍。

本文不会对MyBatis作详细说明,大象还是假定阅读本文的朋友对MyBatis(ibatis)有最基本的了解,只有这样才能较好的理解本文的内容。

关于MyBatis请查看它的官方文档及其它参考资料,本文不作详细讨论。

一、工程结构图上面这是典型的Maven项目结构形式,使用本地仓库管理jar包的依赖,使用插件打包编译发布非常方便,让我们从传统的开发方式中解放出来,大家都快来使用Maven构建项目吧!二、映射文件使用MyBatis进行持久化操作,需要设置一个映射文件,一般来说,每张表对应一个实体对象和一个mapper映射文件。

而MyBatis里面没有像Hibernate那样复杂的关联关系,所以,它的每个实体类其实就是一个很普通的POJO类。

而映射文件中,都是SQL语句,下面就是示例中RoleMapper.xml的代码片段。

那么,MyBatis是如何将数据库字段与POJO对象进行映射的呢?这是在它的内部,会将到得的结果或结构集,与我们定义的POJO对象属性进行映射,规则是,属性首字母小写,使用驼峰式命名方式,而字段则是单词与单词间,用下划线连接。

比如:数据库有个USER_NAME字段,那么与它对应的属性就应该是userName。

如果字段命名没有使用下划线,那么属性可以直接定义成该单词。

比如,NAME字段,它的属性就是name。

三、基于namespace接口与公用dao的区别从MyBatis3.0开始,对mapper中的namespace属性新增了一个特性:可以指定具体的接口来作为持久化操作类,在接口中定义与映射文件中id属性值相同的方法,MyBatis会自动去绑定和执行对应的SQL语句。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.需求说明实现用户通过数据库验证登录需求,采用Myeclipse+Tomcat 6.0+Mysql 5.0+JDK 1.62.数据库表开发所用是Mysql数据库,只建立单张用户表T_USER,表结构如下:sql语句如下:CREATE TABLE `t_user` (`ID` int(11) NOT NULL auto_increment,`USERNAME` varchar(255) default NULL,`PASSWORD` varchar(255) default NULL,PRIMARY KEY (`ID`));3.构建源代码目录4.用到的jar包(见附件Archive.rar)5.各项Xml配置文件详解(1)web.xml文件(Tomcat使用)服务器根据配置内容初始化spring框架,springmvc框架和log4j日志框架<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><!-- 应用程序名称 --><display-name>ISS</display-name><!-- 应用程序描述说明性文字 --><description>Spring,SpringMvc,Ibatis</description><!-- ServletContext初始化参数 --><context-param><param-name>webAppRootKey</param-name><param-value>spring_springmvc_ibatis.root</param-value></context-param><context-param><param-name>log4jConfigLocation</param-name><param-value>/WEB-INF/classes/log4j.properties</param-valu e></context-param><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/applicationContext.xml</param-value ></context-param><!-- 字符过滤,防止添加到数据库的数据为乱码 --><filter><filter-name>characterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFil ter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- web权限配置 --><filter><filter-name>springSecurityFilterChain</filter-name><filter-class>org.springframework.web.filter.DelegatingFil terProxy</filter-class></filter><filter-mapping><filter-name>springSecurityFilterChain</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 配置监听器,用于初始化 --><listener><listener-class>org.springframework.web.util.Log4jConfigLi stener</listener-class></listener><listener><listener-class>org.springframework.web.context.ContextLoaderList ener</listener-class></listener><!-- Servlet初始化参数,配置springmvc模块 --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet< /servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/springmvc-servlet.xml</param-value> </init-param><load-on-startup>2</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 配置session存在时间 --><session-config><session-timeout>60</session-timeout></session-config><!-- 默认起始页面 --><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- 异常跳转页面 --><error-page><exception-type>ng.Exception</exception-type><location>/WEB-INF/jsp/exception.jsp</location></error-page></web-app>(2)springmvc-servlet.xml(Springmvc框架配置文件)该文件是springmvc框架配置文件,也是它的核心文件<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:mvc="/schema/mvc"xmlns:context="/schema/context" xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.0.xsd /schema/mvc/schema/mvc/spring-mvc-3.0.xsd/schema/context/schema/context/spring-context-3.0. xsd"><!-- 自动扫描,完成bean创建和依赖注入 --><context:component-scan base-package="com.archie"/><!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationM ethodHandlerAdapter"/><!-- 视图解析器 --><bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewR esolver"><property name="viewClass"value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" value="/WEB-INF/views/"/><property name="suffix" value=".jsp"/></bean><!-- 异常解析器 --><bean id="simpleMappingExceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExcep tionResolver"><property name="exceptionMappings"><props><propkey="org.springframework.web.multipart.MaxUploadSizeExceededExcep tion">common/fileerror</prop></props></property></bean></beans>(3)applicationContext.xml(Spring框架配置文件)<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:mvc="/schema/mvc"xmlns:context="/schema/context" xmlns:aop="/schema/aop"xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.0.xsd /schema/mvc/schema/mvc/spring-mvc-3.0.xsd/schema/context/schema/context/spring-context-3.0. xsd/schema/tx/schema/tx/spring-tx-3.0.xsd /schema/aop/schema/aop/spring-aop-3.0.xsd" default-autowire="byName"><!-- 自动扫描 --><context:component-scan base-package="com.archie"/><!-- 启动spring注解,当自动扫描启动后,该配置可以去掉<context:annotation-config /> --><!-- 启动spring注解,等同于 context:annotation-config<beanclass="monAnnotationBea nPostProcessor"/><beanclass="org.springframework.beans.factory.annotation.AutowiredAnno tationBeanPostProcessor"/><beanclass="org.springframework.beans.factory.annotation.PersistenceAn notationBeanPostProcessor"/><beanclass="org.springframework.beans.factory.annotation.RequiredAnnot ationBeanPostProcessor"/> --><!-- 配置数据源属性文件 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlacehold erConfigurer"><property name="locations"><list><value>jdbc.properties</value></list></property></bean><!-- 配置数据源 --><bean id="dataSource"class="mons.dbcp.BasicDataSource"><property name="driverClassName" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></bean><!-- 配置SqlMapClient对象 --><bean id="sqlMapClient"class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="sqlMapConfig.xml"/><property name="dataSource" ref="dataSource"/></bean><!--根据sqlMapClien创建一个SqlMapClient模版类--><bean id="sqlMapClientTemplate"class="org.springframework.orm.ibatis.SqlMapClientTemplate"><property name="sqlMapClient" ref="sqlMapClient"/></bean><!-- 配置事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionM anager"><property name="dataSource" ref="dataSource"/></bean><!-- 启动spring事务注解,事务注解尽在此 --><tx:annotation-driven transaction-manager="transactionManager"/><!-- 配置事务特性<tx:advice id="txAdvice"transaction-manager="transactionManager"><tx:attributes><tx:method name="select*" read-only="true"propagation="REQUIRED"/><tx:method name="find*" read-only="true"propagation="REQUIRED"/><tx:method name="save*" propagation="REQUIRED"isolation="REPEATABLE_READ"/><tx:method name="update*" propagation="REQUIRED"isolation="REPEATABLE_READ"/><tx:method name="add*" propagation="REQUIRED"isolation="REPEATABLE_READ"/><tx:method name="delete*" propagation="REQUIRED"isolation="REPEATABLE_READ"/><tx:method name="*" read-only="true"/></tx:attributes></tx:advice> --><!-- 配置事务代理拦截器<bean id="baseTransactionProxy" abstract="true"class="org.springframework.transaction.interceptor.Transac tionProxyFactoryBean"><property name="transactionManager"><ref bean="transactionManager"/></property><property name="transactionAttributes"><props><prop key="insert*">PROPAGATION_REQUIRED</prop><prop key="update*">PROPAGATION_REQUIRED</prop><prop key="delete*">PROPAGATION_REQUIRED</prop><prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props></property></bean> --><!-- 配置哪些类的方法需要进行事务管理<aop:config><aop:pointcut id="baseServiceMethods" expression="execution(* com.archie.service.*.*(..))"/><aop:advisor advice-ref="txAdvice"pointcut-ref="baseServiceMethods"/></aop:config><aop:aspectj-autoproxy /> --><!-- 配置Dao实例<bean id="userDao" class="erDao"><property name="sqlMapClient" ref="sqlMapClient"/></bean> --><!-- 配置Service实例<bean id="userService" class="erService"><property name="userDao" ref="userDao"/></bean> --><!-- 添加了事务的管理类<bean id="userManager" parent="baseTransactionProxy"><property name="target"><bean class="erService"/></property></bean> --></beans>(4)jdbc.properties(数据源属性文件)数据源连接信息的源出处,目前配置了三种数据库Oracle,DB2和Mysql# Database Connectivity# Oracle#driver = oracle.jdbc.driver.OracleDriver#url = jdbc:oracle:thin:@localhost:1521:oracl#username = scott#password = tiger# DB2#driver = com.ibm.db2.jcc.DB2Driver#url = jdbc:db2://10.1.10.162:50000/mydb#username = root#password = root# Mysqldriver = com.mysql.jdbc.Driverurl =jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncodin g=utf-8username = rootpassword = 1234initialPoolSize = 1minPoolSize = 1maxPoolSize =10(5)log4j.properties(log4j框架属性文件)log4j日志属性配置文件# log4j.propertieslog4j.rootLogger=warn,consolelog4j.appender.console=org.apache.log4j.ConsoleAppenderyout=org.apache.log4j.PatternLayoutyout.ConversionPattern=[%d] [%t](%F:%L) %-5p %c - %m%nlog4j.appender.console.Encoding=GB18030log4j.appender.file=org.apache.log4j.RollingFileAppenderlog4j.appender.file.MaxFileSize=10240KBlog4j.appender.file.MaxBackupIndex=100log4j.appender.file.Encoding=GB18030yout=org.apache.log4j.PatternLayoutyout.ConversionPattern=[%d] [%t](%F:%L) %-5p %c - %m%nlog4j.appender.ROLLING_FILE_CUSTOMER=org.apache.log4j.RollingFile Appenderlog4j.appender.ROLLING_FILE_CUSTOMER.Threshold=debuglog4j.appender.ROLLING_FILE_CUSTOMER.Append=truelog4j.appender.ROLLING_FILE_CUSTOMER.MaxFileSize=1024KBlog4j.appender.ROLLING_FILE_CUSTOMER.MaxBackupIndex=30log4j.appender.ROLLING_FILE_yout=org.apache.log4j.Patt ernLayoutlog4j.appender.ROLLING_FILE_yout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%nlog4j.appender.ROLLING_FILE_WORKMANAGER=org.apache.log4j.RollingF ileAppenderlog4j.appender.ROLLING_FILE_WORKMANAGER.Threshold=debuglog4j.appender.ROLLING_FILE_WORKMANAGER.Append=truelog4j.appender.ROLLING_FILE_WORKMANAGER.MaxFileSize=1024KBlog4j.appender.ROLLING_FILE_WORKMANAGER.MaxBackupIndex=30log4j.appender.ROLLING_FILE_yout=org.apache.log4j.P atternLayoutlog4j.appender.ROLLING_FILE_yout.ConversionPattern= %d - %c:%L - %-5p %c %x - %m%nlog4j.appender.ROLLING_FILE_RSS=org.apache.log4j.RollingFileAppen derlog4j.appender.ROLLING_FILE_RSS.Threshold=debuglog4j.appender.ROLLING_FILE_RSS.Append=truelog4j.appender.ROLLING_FILE_RSS.MaxFileSize=1024KBlog4j.appender.ROLLING_FILE_RSS.MaxBackupIndex=30log4j.appender.ROLLING_FILE_yout=org.apache.log4j.PatternLa youtlog4j.appender.ROLLING_FILE_yout.ConversionPattern=%d - %c:%L - %-5p %c %x - %m%n(6)sqlMapConfig.xml(Ibatis框架配置文件)该文件主要负责指定sql映射文件,即与model层对象对应的映射文件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMapConfig PUBLIC "-////DTD SQL Map Config 2.0//EN""/dtd/sql-map-config-2.dtd"><sqlMapConfig><!-- 配置settings --><settings lazyLoadingEnabled="true"useStatementNamespaces="false"/><!-- 配置sql映射文件 --><sqlMap resource="com/archie/model/User.xml"/></sqlMapConfig>6.Java代码编写根据包目录,可以看出分成model层,dao层,service层和web层,另外附加test层,用于java环境测试(1)model层(User.java+User.xml)User.java代码package com.archie.model;public class User {private int id;private String username;private String password;public User(){}public User(int id){this.id = id;}public User(int id, String username){this.id = id;ername = username;}public User(String username, String password) {ername = username;this.password = password;}public User(int id, String username, String password){this.id = id;ername = username;this.password = password;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {ername = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}User.xml代码(model层对象的sql映射文件,被dao层调用,本质是sql语句集合,所有相关的sql均于此)<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMap PUBLIC "-////DTD SQL Map 2.0//EN" "/dtd/sql-map-2.dtd"><sqlMap namespace="User"><typeAlias alias="User" type="er"/><select id="findAllUser" resultClass="User" >select * from t_user</select><select id="findUserByID" resultClass="User"parameterClass="int">select * from t_user where id=#id#</select><select id="getTotalCount" resultClass="int">select count(*) from t_user</select><select id="searchUsers" resultClass="User"parameterClass="User">select * from t_user<dynamic prepend="where"><!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 --><isNotEmpty prepend="and" property="username">(username like '%$username$%')</isNotEmpty><isNotEmpty prepend="and" property="password">(password like '%$password$%')</isNotEmpty></dynamic></select><select id="findUserByNameAndPassword" resultClass="User" parameterClass="User">select * from t_user where username=#username# and password=#password#</select><insert id="insertUser" parameterClass="User">insert into t_user(id,username,password)values(null,#username#,#password#)</insert><update id="updateUser" parameterClass="User">update t_userset username = #username#,password=#password#where id=#id#</update><delete id="deleteUser" parameterClass="int">delete from t_user where id=#id#</delete><delete id="deleteUserByLike" parameterClass="User">delete from t_user<dynamic prepend="where"><!-- 模糊查询,用$表示文本替换,而用#表示替换PrepareStatement中的?号 --><isNotEmpty prepend="and" property="username">(username like '%$username$%')</isNotEmpty><isNotEmpty prepend="and" property="password">(password like '%$password$%')</isNotEmpty></dynamic></delete></sqlMap>(2)dao层(数据服务层,BaseDao.java+UserDao.java)BaseDao.java(公共Dao,其他Dao均继承它)package com.archie.dao;import javax.annotation.PostConstruct;import javax.annotation.Resource;importorg.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.ibatis.sqlmap.client.SqlMapClient;public class BaseDao extends SqlMapClientDaoSupport {@Resource(name="sqlMapClient") //通过bean名称注入private SqlMapClient sqlMapClient;@PostConstruct //完成sqlMapClient初始化工作public void initSqlMapClient(){super.setSqlMapClient(sqlMapClient);}UserDao.java(user数据服务层)package com.archie.dao;import java.util.List;import ponent;import er;@Component //将UserDao类注入到bean里面public class UserDao extends BaseDao {public boolean addUser(User user) throws Exception{User bean =(User)getSqlMapClientTemplate().insert("insertUser", user);return bean != null ? true : false;}public boolean deleteUser(int id) throws Exception{int result =getSqlMapClientTemplate().delete("deleteUser", id);return result > 0 ? true : false;}public User getUserById(int id) throws Exception{return(User)getSqlMapClientTemplate().queryForObject("findUserByID", id);}@SuppressWarnings("unchecked")public List getAllUsers() throws Exception{returngetSqlMapClientTemplate().queryForList("findAllUser");}public boolean updateUser(User user) throws Exception{ int result =getSqlMapClientTemplate().update("updateUser", user);return result > 0 ? true : false;}public User getUserByNameAndPassword(User user) throws Exception{return(User)getSqlMapClientTemplate().queryForObject("findUserByNameAnd Password", user);}public int getTotalCount() throws Exception{return(Integer)getSqlMapClientTemplate().queryForObject("getTotalCount" );}@SuppressWarnings("unchecked")public List getUsersByLike(User user) throws Exception{returngetSqlMapClientTemplate().queryForList("searchUsers", user);}public int deleteUserByLike(User user) throws Exception{ int result =getSqlMapClientTemplate().delete("deleteUserByLike", user);if (result > 0) {System.out.println("模糊删除成功!");}else {System.out.println("没有匹配的记录1");}return result;}}(3)service层(业务服务层,UserService.java)UserService.java代码如下package com.archie.service;import java.util.List;import javax.annotation.Resource;import ponent;import org.springframework.transaction.annotation.Transactional;import erDao;import er;@Component //将UserService类注入到bean里面@Transactional //注入事务管理public class UserService {@Resource(name="userDao") // 通过名称注入到bean里面private UserDao userDao;public User login(User user) throws Exception{return userDao.getUserByNameAndPassword(user);}public void addUser(User user) throws Exception{userDao.addUser(user);}public void deleteUser(int id) throws Exception{boolean bool = userDao.deleteUser(id);if (!bool) {System.out.println("删除的记录不存在!");throw new RuntimeException();}}public User getUserById(int id) throws Exception{User user = userDao.getUserById(id);if (user == null) {return null;}return userDao.getUserById(id);}public void updateUser(User user) throws Exception{userDao.updateUser(user);}public int getTotalCount() throws Exception{return userDao.getTotalCount();}@SuppressWarnings("unchecked")public List getUsersByLike(User user) throws Exception{return userDao.getUsersByLike(user);}public int deleteUserByLike(User user) throws Exception{ return userDao.deleteUserByLike(user);}public void insertUsers(List<User> list) throws Exception{ for (int i = 0; i < list.size(); i++) {if (i > 3) {System.out.println("列表太长,中断事务");throw new RuntimeException("中断事务异常,当列表长度大于3的时候故意抛出,看看事务是否回滚");}User user = list.get(i);userDao.addUser(user);}}}(4)web层(界面控制层,UserController.java)UserController.javapackage com.archie.web;import javax.annotation.Resource;import javax.servlet.http.HttpSession;import javax.validation.Valid;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;import er;import erService;@Controller@RequestMapping("/user/*")public class UserController {@Resource(name="userService")private UserService userService;private final String LIST="redirect:/detail";/*** 登录* @param user* @param session* @return*/@RequestMapping("/login")public ModelAndView login(@Valid User user,BindingResult result,HttpSession session) throws Exception{if(!result.hasErrors()){User loginUser=userService.login(user);if(loginUser!=null){session.setAttribute("USER", loginUser);return new ModelAndView(LIST);}else{return new ModelAndView("redirect:/");}}else{ModelAndView view=new ModelAndView();view.setViewName("redirect:/");view.addObject("error", result.getAllErrors());return view;}}/*** 跳转至添加页* @return*/@RequestMapping(value="/toAdd",method=RequestMethod.GET) public ModelAndView toAdd(){return new ModelAndView("user/add");}/*** 保存* @param user* @return*/@RequestMapping(value="/add",method=RequestMethod.POST)public ModelAndView add(@Valid User user,BindingResult result) throws Exception{if(result.hasErrors()){return new ModelAndView("user/add","error",result.getAllErrors());}else{userService.addUser(user);return new ModelAndView(LIST);}}/*** 根据ID删除* @param id* @return*/@RequestMapping(value="/delete/{id}")public ModelAndView delete(@PathVariable int id) throws Exception{userService.deleteUser(id);return new ModelAndView(LIST);}/*** 跳转至编辑页面* @param id* @return*/@RequestMapping(value="/edit/{id}")public ModelAndView edit(@PathVariable int id) throws Exception{ User user=userService.getUserById(id);return new ModelAndView("user/edit","user",user);}/*** 编辑* @param user* @return*/@RequestMapping(value="/edit")public ModelAndView update(@Valid User user,BindingResult result)throws Exception{ModelAndView view=new ModelAndView();if(result.hasErrors()){view.addObject("error", result.getAllErrors());view.setViewName("user/edit");return view;}else{userService.updateUser(user);return new ModelAndView(LIST);}}}(5)test层(Java环境下测试)TestUserController.javapackage com.archie.test;import java.util.ArrayList;import java.util.List;import org.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContex t;import er;import erService;public class TestUserController {public static void main(String[] args) throws Exception{ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");UserService userService =(UserService)context.getBean("userService");List<User> list = new ArrayList<User>();list.add(new User("wang", "wang"));list.add(new User("wang", "wang"));list.add(new User("wang", "wang"));userService.insertUsers(list);System.out.println("恭喜恭喜,添加成功!");userService.deleteUser(26);System.out.println("恭喜恭喜,删除成功!");User beanUser = userService.getUserById(21);if (beanUser != null) {System.out.println("恭喜恭喜,查找成功!");}else {System.out.println("不好意思,您所查找的用户不存在!");}int totalCount = userService.getTotalCount();System.out.println("TotalCount="+totalCount);int result = userService.deleteUserByLike(newUser("wang","wang"));System.out.println("模糊删除的记录条数是:"+result);List users = userService.getUsersByLike(newUser("meimei","1234"));if (users == null || users.size() == 0) {System.out.println("没有匹配的记录2");}else {for (int i = 0; i < users.size(); i++) {User user = (User)users.get(i);System.out.println("username="+user.getUsername()+",passwo rd="+user.getPassword());}}System.out.println("length="+users.size());}}。

相关文档
最新文档