Spring轻量级框架:不具备侵入性;
mybatis是一个基于Java的持久层框架。mybatis提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
Spring+mybatis 工作这么多年发现十个公司九个在用当然还会加一些其他的框架搭配,更别说分布式架构。总之学好Spring+mybatis走遍天下都不怕
好了不多说了上代码吧
不要在意项目名称这后面我还要改成dubbo的提供者,后面我会写到博客
首先讲一下web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> --> <!--<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> --> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <!-- 默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> |
DispatcherServlet主要用作职责调度工作,本身主要用于控制流程
classpath:spring/spring-*.xml 这前面为甚么要加个classpath呢?编译之后会在项目的classes里面找的是编译之后的路径
"/"会去匹配所有/ 结尾的链接
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/schema?useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root |
配置文件没什么好说的无非就是数据库的一些东西
spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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"> <!-- 配置整合mybatis过程 --> <!-- 1.配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2.数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置连接池属性 --> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- c3p0连接池的私有属性 --> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <!-- 关闭连接后不自动commit --> <property name="autoCommitOnClose" value="false" /> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="10000" /> <!-- 当获取连接失败重试次数 --> <property name="acquireRetryAttempts" value="2" /> </bean> <!-- 3.配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 扫描entity包 使用别名 --> <property name="typeAliasesPackage" value="com.zkb.entity" /> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.zkb.dao" /> </bean> <context:component-scan base-package="com.zkb" /> <!-- 扫描所有注解类 --> </beans> |
用的是Spring啊,所以注解这个要注意,用的是c3p0的连接池
好了mybatis可以用工具来生成代码,太方便了后面放链接
我就直接粘代码啦
package com.zkb.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.zkb.service.UsermboService; @Controller @RequestMapping("/usermbo") public class UsermboController { @Autowired private UsermboService usermboService; @RequestMapping(value = "/insert", method = RequestMethod.GET) public String insert() { try { usermboService.insertUsermbo(); return "ok"; } catch (Exception e) { e.printStackTrace(); return "error"; } } } |
package com.zkb.dao; import com.zkb.entity.Usermbo; public interface UsermboDao { int deleteByPrimaryKey(Integer userid); int insert(Usermbo record); int insertSelective(Usermbo record); Usermbo selectByPrimaryKey(Integer userid); int updateByPrimaryKeySelective(Usermbo record); int updateByPrimaryKey(Usermbo record); } |
package com.zkb.entity; import java.io.Serializable; public class Usermbo implements Serializable{ private static final long serialVersionUID = 1L; private Integer userid; private String username; private Integer userage; public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getUserage() { return userage; } public void setUserage(Integer userage) { this.userage = userage; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } Usermbo other = (Usermbo) that; return (this.getUserid() == null ? other.getUserid() == null : this.getUserid().equals(other.getUserid())) && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername())) && (this.getUserage() == null ? other.getUserage() == null : this.getUserage().equals(other.getUserage())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUserid() == null) ? 0 : getUserid().hashCode()); result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode()); result = prime * result + ((getUserage() == null) ? 0 : getUserage().hashCode()); return result; } } |
package com.zkb.service.Impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zkb.dao.UsermboDao; import com.zkb.entity.Usermbo; import com.zkb.service.UsermboService; @Service public class UsermboServiceImpl implements UsermboService { @Autowired private UsermboDao usermboDao; @Override public void insertUsermbo() { // TODO Auto-generated method stub Usermbo mo = new Usermbo(); mo.setUserid(12987654); mo.setUserage(25); mo.setUsername("zhu"); usermboDao.insertSelective(mo); } } |
package com.zkb.service; public interface UsermboService { void insertUsermbo(); } |
<?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.zkb.dao.UsermboDao"> <resultMap id="BaseResultMap" type="com.zkb.entity.Usermbo"> <id column="USERID" jdbcType="INTEGER" property="userid" /> <result column="USERNAME" jdbcType="VARCHAR" property="username" /> <result column="USERAGE" jdbcType="INTEGER" property="userage" /> </resultMap> <sql id="Base_Column_List"> USERID, USERNAME, USERAGE </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from usermbo where USERID = #{userid,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from usermbo where USERID = #{userid,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.zkb.entity.Usermbo"> insert into usermbo (USERID, USERNAME, USERAGE ) values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{userage,jdbcType=INTEGER} ) </insert> <insert id="insertSelective" parameterType="com.zkb.entity.Usermbo"> insert into usermbo <trim prefix="(" suffix=")" suffixOverrides=","> <if test="userid != null"> USERID, </if> <if test="username != null"> USERNAME, </if> <if test="userage != null"> USERAGE, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="userid != null"> #{userid,jdbcType=INTEGER}, </if> <if test="username != null"> #{username,jdbcType=VARCHAR}, </if> <if test="userage != null"> #{userage,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zkb.entity.Usermbo"> update usermbo <set> <if test="username != null"> USERNAME = #{username,jdbcType=VARCHAR}, </if> <if test="userage != null"> USERAGE = #{userage,jdbcType=INTEGER}, </if> </set> where USERID = #{userid,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.zkb.entity.Usermbo"> update usermbo set USERNAME = #{username,jdbcType=VARCHAR}, USERAGE = #{userage,jdbcType=INTEGER} where USERID = #{userid,jdbcType=INTEGER} </update> </mapper> |
建表语句
CREATE TABLE `usermbo` ( `USERID` int(11) NOT NULL default '0', `USERNAME` varchar(50) default NULL, `USERAGE` int(11) default NULL, PRIMARY KEY (`USERID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
好了到此为止放到tomcat里面然后进入http://127.0.0.1:8080/SpringDubboProvider/usermbo/insert之后就会发现数据库里面多了一条数据
mybatis自动生成策略下载链接 http://download.youkuaiyun.com/download/qq_14926283/9834117 良心不要积分啊
本文demo代码下载: