Spring+Mybatis实战教程
2016-09-02 10:13
211 查看
1、ORM的基本思想
是将表与表之间的操作,映射成对象和对象之间的操作,就是通过操作实体类来达到操作表的目的。从而避免冗长的持久层代码,专注于业务逻辑
1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.
2. 由sessionfactory 产生 session
3. 在session 中完成对数据的增删改查和事务提交等.
4. 在用完之后关闭session 。
5. 在java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。
和hibernate一样作为持久层的框架,mybatis是一个轻量级半ORM框架,开发者自行定义sql,因此更加灵活。
开发工具:STS,Sql Developer,Tomcat7,Maven
开发环境:SpringMVC,MyBatis,Oracle
项目结构:
这里使用国内一个叫tk.mybatis的工具,相较于原生态的mybatis,它帮助我们做了很多实用的事情,大多数情况下我们需要在原生态mybatis上加工的想法它基本上都已经有很好的实现。
第一步,添加Maven依赖:
第二步,在root-context.xml里面注册mybatis配置:
web.xml
servlet-context.xml
第三步,测试:
实体类
mapper接口:
SUserMapper.xml:
com.wang.ff.entity.sUser.service.UserService类:
WEB-INF/views/user.jsp:
启动项目后访问成功获取数据
是将表与表之间的操作,映射成对象和对象之间的操作,就是通过操作实体类来达到操作表的目的。从而避免冗长的持久层代码,专注于业务逻辑
1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.
2. 由sessionfactory 产生 session
3. 在session 中完成对数据的增删改查和事务提交等.
4. 在用完之后关闭session 。
5. 在java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。
和hibernate一样作为持久层的框架,mybatis是一个轻量级半ORM框架,开发者自行定义sql,因此更加灵活。
开发工具:STS,Sql Developer,Tomcat7,Maven
开发环境:SpringMVC,MyBatis,Oracle
项目结构:
这里使用国内一个叫tk.mybatis的工具,相较于原生态的mybatis,它帮助我们做了很多实用的事情,大多数情况下我们需要在原生态mybatis上加工的想法它基本上都已经有很好的实现。
第一步,添加Maven依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wang</groupId> <artifactId>ff</artifactId> <name>spring-1</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> 4000 <java-version>1.6</java-version> <org.springframework-version>3.1.1.RELEASE</org.springframework-version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> </properties> <dependencies> <span style="color:#ff0000;"><!-- Spring依赖 --></span> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.1.RELEASE</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <span style="color:#ff0000;"><!-- mybatis --></span> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!-- mybatis自动生成代码 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.4.0</version> </dependency> <span style="color:#ff0000;"> <!-- dbcp连接池依赖 --> </span> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <plugins> <!-- tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <uriEncoding>UTF-8</uriEncoding> <path>/testShiro</path> <port>8888</port> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <!-- 插件的初始配置 --> <configuration> <!-- 指定插件运行的generator.xml文件位置 --> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <!-- 允许移动生成的文件--> <verbose>true</verbose> <!-- 允许覆盖生成的文件--> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.4.0</version> </dependency> </dependencies> </plugin> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> </build> </project>关于mybatis自动生成代码可以参考我的另一篇博文http://blog.csdn.net/biaozhun90/article/details/52223246
第二步,在root-context.xml里面注册mybatis配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> <context:property-placeholder ignore-unresolvable="true" location="classpath:param.properties" /> <context:annotation-config /> <context:component-scan base-package="com.wang"/> <!-- 数据源配置, 使用DBCP数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling Info --> <property name="maxActive" value="${dbcp.maxActive}" /> <property name="maxIdle" value="${dbcp.maxIdle}" /> <property name="defaultAutoCommit" value="false" /> <!-- 连接Idle一个小时后超时 --> <property name="timeBetweenEvictionRunsMillis" value="3600000" /> <property name="minEvictableIdleTimeMillis" value="3600000" /> </bean> <!-- sqlSessionFactory工厂注册 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 自动注册mybatis mapper bean --> <!-- 注意,没有必要去指定SqlSessionFactory或SqlSessionTemplate, 因为MapperScannerConfigurer将会创建 MapperFactoryBean,之后自动装配。 但是,如果你使 用了一个以上的DataSource,那 么自动装配可能会失效。 这种情况下,你可以使用 sqlSessionFactoryBeanName或sqlSessionTemplateBeanName 属性来设置正确的 bean名称来使用。 --> <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.wang.ff.entity.*.persistence" /> <property name="properties"> <value> mappers=tk.mybatis.mapper.common.Mapper ORDER=BEFORE </value> </property> </bean> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="com.wang.ff" /> </beans:beans>
第三步,测试:
实体类
package com.wang.ff.entity.sUser.domain; import java.math.BigDecimal; public class SUser { private BigDecimal id; private String userName; private String password; public BigDecimal getId() { return id; } public void setId(BigDecimal id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } }
mapper接口:
package com.wang.ff.entity.sUser.persistence; import com.wang.ff.entity.sUser.domain.SUser; import java.math.BigDecimal; public interface SUserMapper { int deleteByPrimaryKey(BigDecimal id); int insert(SUser record); int insertSelective(SUser record); SUser selectByPrimaryKey(BigDecimal id); int updateByPrimaryKeySelective(SUser record); int updateByPrimaryKey(SUser record); SUser b6a8 getUserByName(String userName); }
SUserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.wang.ff.entity.sUser.persistence.SUserMapper" > <resultMap id="BaseResultMap" type="com.wang.ff.entity.sUser.domain.SUser" > <id column="ID" property="id" jdbcType="DECIMAL" /> <result column="USER_NAME" property="userName" jdbcType="VARCHAR" /> <result column="PASSWORD" property="password" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > ID, USER_NAME, PASSWORD </sql> <select id="getUserByName" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from S_USER where user_name = #{userName,jdbcType=VARCHAR} </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.math.BigDecimal" > select <include refid="Base_Column_List" /> from S_USER where ID = #{id,jdbcType=DECIMAL} </select> <delete id="deleteByPrimaryKey" parameterType="java.math.BigDecimal" > delete from S_USER where ID = #{id,jdbcType=DECIMAL} </delete> <insert id="insert" parameterType="com.wang.ff.entity.sUser.domain.SUser" > insert into S_USER (ID, USER_NAME, PASSWORD ) values (#{id,jdbcType=DECIMAL}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR} ) </insert> <insert id="insertSelective" parameterType="com.wang.ff.entity.sUser.domain.SUser" > insert into S_USER <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > ID, </if> <if test="userName != null" > USER_NAME, </if> <if test="password != null" > PASSWORD, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=DECIMAL}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.wang.ff.entity.sUser.domain.SUser" > update S_USER <set > <if test="userName != null" > USER_NAME = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > PASSWORD = #{password,jdbcType=VARCHAR}, </if> </set> where ID = #{id,jdbcType=DECIMAL} </update> <update id="updateByPrimaryKey" parameterType="com.wang.ff.entity.sUser.domain.SUser" > update S_USER set USER_NAME = #{userName,jdbcType=VARCHAR}, PASSWORD = #{password,jdbcType=VARCHAR} where ID = #{id,jdbcType=DECIMAL} </update> </mapper>
com.wang.ff.entity.sUser.service.UserService类:
package com.wang.ff.entity.sUser.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wang.ff.entity.sUser.domain.SUser; import com.wang.ff.entity.sUser.persistence.SUserMapper; @Service public class UserService { @Autowired private SUserMapper userMapper; public SUser getUserByName(String userName){ return userMapper.getUserByName(userName); } }com.wang.ff.controller.UserController:
package com.wang.ff.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.wang.ff.entity.sUser.domain.SUser; import com.wang.ff.entity.sUser.service.UserService; @Controller @RequestMapping(value="/user") public class UserController { @Resource private UserService userService; @RequestMapping(value="/getUser") public ModelAndView getUser(String userName){ ModelAndView mv = new ModelAndView("user"); SUser user = this.userService.getUserByName(userName); mv.addObject("user",user); return mv; } }
WEB-INF/views/user.jsp:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %> <html> <head> <title>Home</title> </head> <body> <h1> Hello world! </h1> <p>name:${user.userName };password:${user.password }</p> </body> </html>
启动项目后访问成功获取数据
相关文章推荐
- mybatis实战教程(mybatis in action)之五:与spring3集成(附源码)
- mybatis实战教程(mybatis in action)之五:与spring3集成(附源码)(转)
- mybatis实战教程(mybatis in action)之五:与spring3集成
- mybatis实战教程(mybatis in action)之五:与spring3集成(附源码)
- mybatis实战教程之五:与spring3集成
- 【备忘】2017年最新 项目实战 Spring Boot视频教程 微服务整合Mybatis
- (实战篇)SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)
- (实战篇)SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)
- mybatis实战教程(mybatis in action),mybatis入门到精通
- mybatis实战教程(mybatis in action)之七:实现mybatis分页(源码下载)(转)
- Maven+Spring+Spring MVC+Mybatis项目实战
- mybatis实战教程(mybatis in action),mybatis入门到精通
- mybatis实战教程(mybatis in action),mybatis入门到精通
- mybatis实战教程(mybatis in action)之二:以接口的方式编程(转)
- mybatis实战教程(mybatis in action),mybatis入门到精通
- mybatis实战教程(mybatis in action),mybatis入门到精通
- Spring.net实战开发教程下载 Spring.net视频教程
- mybatis实战教程(mybatis in action)之三:实现数据的增删改查(转)
- Spring.net实战开发教程下载
- mybatis实战教程(mybatis in action)之九:mybatis 代码生成工具的使用(转)