发表于: 2016-05-31 23:45:40

0 1414


1. 安装数据库 mysql

2. 创建用户


create database ww default character set utf8;


create user 'dev'@'%' identified by '!abcd1234';

grant all privileges on *.* to 'dev'@'%' with grant option;


配置 my.cnf


bind-address = 0.0.0.0 //绑定所有的ip


sudo service mysql restart; //重启mysql服务,使修改后的配置生效


DROP  TABLE if EXISTS user;
create table IF NOT EXISTS user(
id int(8) auto_increment PRIMARY KEY comment 'user id',
 name varchar(128) comment 'user name',
 password varchar(32) comment 'user password',
 nick_name varchar(128) comment 'nickName',
 create_at BIGINT(8) comment 'timestamp of create',
 update_at BIGINT(8) comment 'timestamp of update',
 key id(id),
 key id_name(id,name)
);



配置maven pom.xml:

<spring.version>4.1.2.RELEASE</spring.version>
<mybatis.spring.version>1.3.0</mybatis.spring.version>
<mybatis.version>3.4.0</mybatis.version>

mybatis.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
       PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   <properties resource="generator.properties"></properties>
   <environments default="development">
       <environment id="development">
           <transactionManager type="JDBC"/>
           <dataSource type="POOLED">
               <property name="driver" value="${jdbc.driverClass}"/>
               <property name="url" value="${jdbc.url}"/>
               <property name="username" value="${jdbc.user}"/>
               <property name="password" value="${jdbc.password}"/>
           </dataSource>
       </environment>
   </environments>
   <mappers>
       <mapper resource="mapper/UserMapper.xml"/>
   </mappers>
</configuration>

generatorConfig.properties:

jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://192.168.199.234:3306/ww
jdbc.user = dev
jdbc.password =!abcd1234

generatorConfig.xml:

<!DOCTYPE generatorConfiguration
       PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
       "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
   <properties resource="generator.properties"/>

   <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
       <property name="beginningDelimiter" value="`"/>
       <property name="endingDelimiter" value="`"/>

       <!--<plugin type="${mapper.plugin}">-->
           <!--<property name="mappers" value="${mapper.Mapper}"/>-->
       <!--</plugin>-->

       <jdbcConnection driverClass="${jdbc.driverClass}"
                       connectionURL="${jdbc.url}"
                       userId="${jdbc.user}"
                       password="${jdbc.password}">
       </jdbcConnection>

       <javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}"/>

       <sqlMapGenerator targetPackage="${targetXMLPackage}"  targetProject="${targetResourcesProject}"/>

       <javaClientGenerator targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}" type="XMLMAPPER" />

       <table tableName="%" >
           <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
       </table>
   </context>
</generatorConfiguration>

生成的UserMapper.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.bude.ww.UserMapper">
 <resultMap id="BaseResultMap" type="com.bude.ww.model.User">
   <!--
     WARNING - @mbggenerated
     This element is automatically generated by MyBatis Generator, do not modify.
     This element was generated on Tue May 31 23:08:50 CST 2016.
   -->
   <id column="id" jdbcType="INTEGER" property="id" />
   <result column="name" jdbcType="VARCHAR" property="name" />
   <result column="password" jdbcType="VARCHAR" property="password" />
   <result column="nick_name" jdbcType="VARCHAR" property="nickName" />
   <result column="create_at" jdbcType="BIGINT" property="createAt" />
   <result column="update_at" jdbcType="BIGINT" property="updateAt" />
 </resultMap>
 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
   <!--
     WARNING - @mbggenerated
     This element is automatically generated by MyBatis Generator, do not modify.
     This element was generated on Tue May 31 23:08:50 CST 2016.
   -->
   delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
 <insert id="insert" parameterType="com.bude.ww.model.User">
   <!--
     WARNING - @mbggenerated
     This element is automatically generated by MyBatis Generator, do not modify.
     This element was generated on Tue May 31 23:08:50 CST 2016.
   -->
   <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
     SELECT LAST_INSERT_ID()
</selectKey>
   insert into user (name, password, nick_name,
create_at, update_at)
values (#{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{nickName,jdbcType=VARCHAR},
#{createAt,jdbcType=BIGINT}, #{updateAt,jdbcType=BIGINT})
</insert>
 <update id="updateByPrimaryKey" parameterType="com.bude.ww.model.User">
   <!--
     WARNING - @mbggenerated
     This element is automatically generated by MyBatis Generator, do not modify.
     This element was generated on Tue May 31 23:08:50 CST 2016.
   -->
   update user
set name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
nick_name = #{nickName,jdbcType=VARCHAR},
create_at = #{createAt,jdbcType=BIGINT},
update_at = #{updateAt,jdbcType=BIGINT}
where id = #{id,jdbcType=INTEGER}
</update>
 <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
   <!--
     WARNING - @mbggenerated
     This element is automatically generated by MyBatis Generator, do not modify.
     This element was generated on Tue May 31 23:08:50 CST 2016.
   -->
   select id, name, password, nick_name, create_at, update_at
from user
where id = #{id,jdbcType=INTEGER}
</select>
 <select id="selectAll" resultMap="BaseResultMap">
   <!--
     WARNING - @mbggenerated
     This element is automatically generated by MyBatis Generator, do not modify.
     This element was generated on Tue May 31 23:08:50 CST 2016.
   -->
   select id, name, password, nick_name, create_at, update_at
from user
</select>
</mapper>

spring mybatis 配置applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns="http://www.springframework.org/schema/beans"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">

   <context:component-scan base-package="com.bude.ww.services"/>

   <context:property-placeholder location="classpath:generator.properties"/>

   <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
       <property name="driverClassName" value="${jdbc.driverClass}"/>
       <property name="url" value="${jdbc.url}"/>
       <property name="username" value="${jdbc.user}"/>
       <property name="password" value="${jdbc.password}"/>

       <property name="filters" value="stat"/>

       <property name="maxActive" value="20"/>
       <property name="initialSize" value="1"/>
       <property name="maxWait" value="60000"/>
       <property name="minIdle" value="1"/>

       <property name="timeBetweenEvictionRunsMillis" value="60000"/>
       <property name="minEvictableIdleTimeMillis" value="300000"/>

       <property name="validationQuery" value="SELECT 'x'"/>
       <property name="testWhileIdle" value="true"/>
       <property name="testOnBorrow" value="false"/>
       <property name="testOnReturn" value="false"/>
   </bean>

   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="mapperLocations">
           <array>
               <value>classpath:mapper/*.xml</value>
           </array>
       </property>
       <property name="typeAliasesPackage" value="com.bude.ww.model"/>
       <property name="plugins">
           <array>
               <bean class="com.github.pagehelper.PageHelper">
                   <property name="properties">
                       <value>
                           dialect=mysql
reasonable=true
supportMethodsArguments=true
params=count=countSql
autoRuntimeDialect=true
</value>
                   </property>
               </bean>
           </array>
       </property>
   </bean>

   <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.bude.ww"/>
       <!-- 3.2.2版本新特性,markerInterface可以起到mappers配置的作用,详细情况需要看Marker接口类 -->
       <property name="markerInterface" value="com.bude.ww.utils.MyMapper"/>
       <!-- 通用Mapper通过属性注入进行配置,默认不配置时会注册Mapper<T>接口
       <property name="properties">
           <value>
               mappers=tk.mybatis.mapper.common.Mapper
           </value>
       </property>
       -->
   </bean>

   <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
       <constructor-arg index="0" ref="sqlSessionFactory"/>
   </bean>

   <aop:aspectj-autoproxy/>

   <aop:config>
       <aop:pointcut id="appService" expression="execution(* com.bude.ww.services..*Service*.*(..))"/>
       <aop:advisor advice-ref="txAdvice" pointcut-ref="appService"/>
   </aop:config>

   <tx:advice id="txAdvice" transaction-manager="transactionManager">
       <tx:attributes>
           <tx:method name="select*" read-only="true"/>
           <tx:method name="find*" read-only="true"/>
           <tx:method name="get*" read-only="true"/>
           <tx:method name="*"/>
       </tx:attributes>
   </tx:advice>

   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource"/>
   </bean>
</beans>

测试用例:

package com.bude;

import com.bude.ww.UserMapper;
import com.bude.ww.model.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
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;

/**
* Created by andy on 2016/5/30.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MybatisTest {
@Autowired
   private SqlSession sqlSession;
   @Test
   public void testMybatisAdd(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
           User user1 = new User();
           user1.setName("lilei");
           user1.setNickName("lilei_hanmeimei");
           user1.setPassword("ll");
           Long current = System.currentTimeMillis();
           user1.setCreateAt(current);
           user1.setUpdateAt(current);

           int ret = mapper.insert(user1);
           Assert.assertEquals(1,ret);

   }

@Test
   public void testMybatisUpdate(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       User user1 = new User();
       user1.setName("lilei");
       user1.setNickName("lilei_hanmeimei");
       user1.setPassword("ll");
       Long current = System.currentTimeMillis();
       user1.setCreateAt(current);
       user1.setUpdateAt(current);
       int ret = mapper.insert(user1);

       System.out.println(user1.getName());
       Integer id = user1.getId();
       user1.setName("updated_for_name");
       mapper.updateByPrimaryKey(user1);
       User newUser = mapper.selectByPrimaryKey(id);
       Assert.assertEquals(user1.getName(),newUser.getName());

   }

@Test
   public void testMybatisDelete(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       User user1 = new User();
       user1.setName("lilei");
       user1.setNickName("lilei_hanmeimei");
       user1.setPassword("ll");
       Long current = System.currentTimeMillis();
       user1.setCreateAt(current);
       user1.setUpdateAt(current);

       int ret = mapper.insert(user1);
       mapper.deleteByPrimaryKey(user1.getId());
       User newUser = mapper.selectByPrimaryKey(user1.getId());
       Assert.assertNull(newUser);
   }

@Test
   public void testMybatisRead(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       User user1 = new User();
       user1.setName("lilei");
       user1.setNickName("lilei_hanmeimei");
       user1.setPassword("ll");
       Long current = System.currentTimeMillis();
       user1.setCreateAt(current);
       user1.setUpdateAt(current);

       int ret = mapper.insert(user1);
       User newUser = mapper.selectByPrimaryKey(user1.getId());
       Assert.assertNotNull(newUser);
   }
}



明天:

task2


返回列表 返回列表
评论

    分享到