MyBatis快速入门(简明浅析易懂)
一、mybatis简介
mybatis是支持普通sql查询,存储过程和高级映射的优秀持久层框架。
mybatis消除了几乎所有的jdbc代码和参数的手工设置以及对结果集的检索封装。
mybatis可以使用简单的xml或注解用于配置和原始映射,将接口和java的pojo(plain old java objects,普通的java对象)映射成数据库中的记录.
jdbc -> dbutils(自动封装) -> mybatis -> hibernate
mybatis是将sql写在xml中,然后去访问数据库。
二、mybatis快速入门
2.1.新建java项目
添加mybatis和mysql的驱动jar:mybatis-3.1.1.jar,mysql-connector-java-5.1.7-bin.jar
2.2.新建表
create database mybatis; use mybatis; create table users(id int primary key auto_increment, name varchar(20), age int); insert into users (name,age) values('tom',12); insert into users (name, age) values('jack',11);
2.3.添加mybatis的配置文件conf.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> <environments default="development"> <environment id="development"> <transactionmanager type="jdbc" /> <datasource type="pooled"> <property name="driver" value="com.mysql.jdbc.driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </datasource> </environment> </environments> </configuration>
2.4.定义表对应的实体类
public class user { private int id; private string name; private int age; //get,set方法 }
2.5.定义操作users表的sql映射文件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.atguigu.mybatis_test.test1.usermapper"> <select id="getuser" parametertype="int" resulttype="com.atguigu.mybatis_test.test1.user"> select * from users where id=#{id} </select> </mapper>
2.6.在conf.xml文件中注册usermapper.xml文件
<mappers> <mapper resource="com/atguigu/mybatis_test/test1/usermapper.xml"/> </mappers>
2.7.编写测试代码:执行定义的select语句
public class test { public static void main(string[] args) throws ioexception { string resource = "conf.xml"; //加载mybatis的配置文件(它也加载关联的映射文件) reader reader = resources.getresourceasreader(resource); //构建sqlsession的工厂 sqlsessionfactory sessionfactory = new sqlsessionfactorybuilder().build(reader); //创建能执行映射文件中sql的sqlsession sqlsession session = sessionfactory.opensession(); //映射sql的标识字符串 string statement = "com.atguigu.mybatis.bean.usermapper"+".selectuser"; //执行查询返回一个唯一user对象的sql user user = session.selectone(statement, 1); system.out.println(user); } }
三、操作users表的crud
3.1.xml的实现
3.1.1.定义sql映射xml文件:
<insert id="insertuser" parametertype="com.atguigu.ibatis.bean.user"> insert into users(name, age) values(#{name}, #{age}); </insert> <delete id="deleteuser" parametertype="int"> delete from users where id=#{id} </delete> <update id="updateuser" parametertype="com.atguigu.ibatis.bean.user"> update users set name=#{name},age=#{age} where id=#{id} </update> <select id="selectuser" parametertype="int" resulttype="com.atguigu.ibatis.bean.user"> select * from users where id=#{id} </select> <select id="selectallusers" resulttype="com.atguigu.ibatis.bean.user"> select * from users </select>
3.1.2.在config.xml中注册这个映射文件
<mapper resource=" com/atguigu/ibatis/bean/usermapper.xml"/>
3.1.3.在dao中调用
public user getuserbyid(int id) { sqlsession session = sessionfactory.opensession(); user user = session.selectone(uri+".selectuser", id); return user; }
3.2.注解的实现
3.2.1.定义sql映射的接口
public interface usermapper { @insert("insert into users(name, age) values(#{name}, #{age})") public int insertuser(user user); @delete("delete from users where id=#{id}") public int deleteuserbyid(int id); @update("update users set name=#{name},age=#{age} where id=#{id}") public int updateuser(user user); @select("select * from users where id=#{id}") public user getuserbyid(int id); @select("select * from users") public list<user> getalluser(); }
3.2.2.在config中注册这个映射接口
<mapper class="com.atguigu.ibatis.crud.ano.usermapper"/>
3.2.3.在dao中调用
public user getuserbyid(int id) { sqlsession session = sessionfactory.opensession(); usermapper mapper = session.getmapper(usermapper.class); user user = mapper.getuserbyid(id); return user; }
四、几个可以优化的地方
4.1.连接数据库的配置可以单独放在一个properties文件中。
## db.properties<br> <properties resource="db.properties"/> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" />
4.2.为实体类定义别名,简化sql映射xml文件中的引用
<typealiases> <typealias type="com.atguigu.ibatis.bean.user" alias="_user"/> </typealiases>
4.3.可以在src下加入log4j的配置文件,打印日志信息
1. 添加jar:
log4j-1.2.16.jar
2.1. log4j.properties(方式一)
log4j.properties, log4j.rootlogger=debug, console #console log4j.appender.console=org.apache.log4j.consoleappender log4j.appender.console.layout=org.apache.log4j.patternlayout log4j.appender.console.layout.conversionpattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.resultset=info log4j.logger.org.apache=info log4j.logger.java.sql.connection=debug log4j.logger.java.sql.statement=debug log4j.logger.java.sql.preparedstatement=debug
2.2. log4j.xml(方式二)
<?xml version="1.0" encoding="utf-8" ?> <!doctype log4j:configuration system "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="stdout" class="org.apache.log4j.consoleappender"> <layout class="org.apache.log4j.patternlayout"> <param name="conversionpattern" value="%-5p %d{mm-dd hh:mm:ss,sss} %m (%f:%l) \n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="debug" /> </logger> <root> <level value="debug" /> <appender-ref ref="stdout" /> </root> </log4j:configuration>
五、解决字段名与实体类属性名不相同的冲突
5.1.准备表和字段
create table orders( order_id int primary key auto_increment, order_no varchar(20), order_price float ); insert into orders(order_no, order_price) values('aaaa', 23); insert into orders(order_no, order_price) values('bbbb', 33); insert into orders(order_no, order_price) values('cccc', 22);
5.2.定义实体类
public class order { private int id; private string orderno; private float price; }
5.3.实现getorderbyid(id)的查询:
方式一: 通过在sql语句中定义别名
<select id="selectorder" parametertype="int" resulttype="_order"> select order_id id, order_no orderno,order_price price from orders where order_id=#{id} </select>
方式二: 通过<resultmap>
<select id="selectorderresultmap" parametertype="int" resultmap="orderresultmap"> select * from orders where order_id=#{id} </select> <resultmap type="_order" id="orderresultmap"> <id property="id" column="order_id"/> <result property="orderno" column="order_no"/> <result property="price" column="order_price"/> </resultmap>
六、实现关联表查询
6.1.一对一关联
6.1.1.提出需求
根据班级id查询班级信息(带老师的信息)
6.1.2.创建表和数据
create table teacher( t_id int primary key auto_increment, t_name varchar(20) ); create table class( c_id int primary key auto_increment, c_name varchar(20), teacher_id int ); alter table class add constraint fk_teacher_id foreign key (teacher_id) references teacher(t_id); insert into teacher(t_name) values('ls1'); insert into teacher(t_name) values('ls2'); insert into class(c_name, teacher_id) values('bj_a', 1); insert into class(c_name, teacher_id) values('bj_b', 2);
6.1.3.定义实体类:
public class teacher { private int id; private string name; } public class classes { private int id; private string name; private teacher teacher; }
6.1.4.定义sql映射文件classmapper.xml
<!-- 方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集 select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=1 --> <select id="getclass3" parametertype="int" resultmap="classresultmap3"> select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=#{id} </select> <resultmap type="_classes" id="classresultmap3"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javatype="_teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- oftype指定students集合中的对象类型 --> <collection property="students" oftype="_student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultmap> <!-- 方式二:嵌套查询:通过执行另外一个sql映射语句来返回预期的复杂类型 select * from class where c_id=1; select * from teacher where t_id=1 //1 是上一个查询得到的teacher_id的值 select * from student where class_id=1 //1是第一个查询得到的c_id字段的值 --> <select id="getclass4" parametertype="int" resultmap="classresultmap4"> select * from class where c_id=#{id} </select> <resultmap type="_classes" id="classresultmap4"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javatype="_teacher" select="getteacher2"></association> <collection property="students" oftype="_student" column="c_id" select="getstudent"></collection> </resultmap> <select id="getteacher2" parametertype="int" resulttype="_teacher"> select t_id id, t_name name from teacher where t_id=#{id} </select> <select id="getstudent" parametertype="int" resulttype="_student"> select s_id id, s_name name from student where class_id=#{id} </select>
6.1.5.测试
@test public void testoo() { sqlsession sqlsession = factory.opensession(); classes c = sqlsession.selectone("com.atguigu.day03_mybatis.test5.oomapper.getclass", 1); system.out.println(c); } @test public void testoo2() { sqlsession sqlsession = factory.opensession(); classes c = sqlsession.selectone("com.atguigu.day03_mybatis.test5.oomapper.getclass2", 1); system.out.println(c); }
6.2.一对多关联
6.2.1.提出需求
根据classid查询对应的班级信息,包括学生,老师
6.2.2.创建表和数据:
create table student( s_id int primary key auto_increment, s_name varchar(20), class_id int ); insert into student(s_name, class_id) values('xs_a', 1); insert into student(s_name, class_id) values('xs_b', 1); insert into student(s_name, class_id) values('xs_c', 1); insert into student(s_name, class_id) values('xs_d', 2); insert into student(s_name, class_id) values('xs_e', 2); insert into student(s_name, class_id) values('xs_f', 2);
6.2.3.定义实体类
public class student { private int id; private string name; } public class classes { private int id; private string name; private teacher teacher; private list<student> students; }
6.2.4.定义sql映射文件classmapper.xml
<!-- 方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集 select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=1 --> <select id="getclass3" parametertype="int" resultmap="classresultmap3"> select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=#{id} </select> <resultmap type="_classes" id="classresultmap3"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javatype="_teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- oftype指定students集合中的对象类型 --> <collection property="students" oftype="_student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultmap> <!-- 方式二:嵌套查询:通过执行另外一个sql映射语句来返回预期的复杂类型 select * from class where c_id=1; select * from teacher where t_id=1 //1 是上一个查询得到的teacher_id的值 select * from student where class_id=1 //1是第一个查询得到的c_id字段的值 --> <select id="getclass4" parametertype="int" resultmap="classresultmap4"> select * from class where c_id=#{id} </select> <resultmap type="_classes" id="classresultmap4"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javatype="_teacher" select="getteacher2"></association> <collection property="students" oftype="_student" column="c_id" select="getstudent"></collection> </resultmap> <select id="getteacher2" parametertype="int" resulttype="_teacher"> select t_id id, t_name name from teacher where t_id=#{id} </select> <select id="getstudent" parametertype="int" resulttype="_student"> select s_id id, s_name name from student where class_id=#{id} </select>
6.2.5.测试
@test public void testom() { sqlsession sqlsession = factory.opensession(); classes c = sqlsession.selectone("com.atguigu.day03_mybatis.test5.oomapper.getclass3", 1); system.out.println(c); } @test public void testom2() { sqlsession sqlsession = factory.opensession(); classes c = sqlsession.selectone("com.atguigu.day03_mybatis.test5.oomapper.getclass4", 1); system.out.println(c); }
七、动态sql与模糊查询
7.1.需求
实现多条件查询用户(姓名模糊匹配, 年龄在指定的最小值到最大值之间)。
7.2.准备数据库和表
create table d_user( id int primary key auto_increment, name varchar(10), age int(3) ); insert into d_user(name,age) values('tom',12); insert into d_user(name,age) values('bob',13); insert into d_user(name,age) values('jack',18); 7.3.conditionuser(查询条件实体类) private string name; private int minage; private int maxage;
7.4.user表实体类
private int id; private string name; private int age;
7.5.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.atguigu.day03_mybatis.test6.usermapper"> <select id="getuser" parametertype="com.atguigu.day03_mybatis.test6.conditionuser" resulttype="com.atguigu.day03_mybatis.test6.user"> select * from d_user where age>=#{minage} and age<=#{maxage} <if test='name!="%null%"'>and name like #{name}</if> </select> </mapper>
7.6.usertest(测试)
public class usertest { public static void main(string[] args) throws ioexception { reader reader = resources.getresourceasreader("conf.xml"); sqlsessionfactory sessionfactory = new sqlsessionfactorybuilder().build(reader); sqlsession sqlsession = sessionfactory.opensession(); string statement = "com.atguigu.day03_mybatis.test6.usermapper.getuser"; list<user> list = sqlsession.selectlist(statement, new conditionuser("%a%", 1, 12)); system.out.println(list); } }
mybatis中可用的动态sql标签
八、调用存储过程
8.1.提出需求
查询得到男性或女性的数量, 如果传入的是0就女性否则是男性
8.2.准备数据库表和存储过程:
create table p_user( id int primary key auto_increment, name varchar(10), sex char(2) ); insert into p_user(name,sex) values('a',"男"); insert into p_user(name,sex) values('b',"女"); insert into p_user(name,sex) values('c',"男"); #创建存储过程(查询得到男性或女性的数量, 如果传入的是0就女性否则是男性) delimiter $ create procedure mybatis.ges_user_count(in sex_id int, out user_count int) begin if sex_id=0 then select count(*) from mybatis.p_user where p_user.sex='女' into user_count; else select count(*) from mybatis.p_user where p_user.sex='男' into user_count; end if; end $ #调用存储过程 delimiter ; set @user_count = 0; call mybatis.ges_user_count(1, @user_count); select @user_count;
8.3.创建表的实体类
public class user { private string id; private string name; private string sex; }
8.4.usermapper.xml
<mapper namespace="com.atguigu.mybatis.test7.usermapper"> <!-- 查询得到男性或女性的数量, 如果传入的是0就女性否则是男性 call mybatis.get_user_count(1, @user_count); --> <select id="getcount" statementtype="callable" parametermap="getcountmap"> call mybatis.get_user_count(?,?) </select> <parametermap type="java.util.map" id="getcountmap"> <parameter property="sex_id" mode="in" jdbctype="integer"/> <parameter property="user_count" mode="out" jdbctype="integer"/> </parametermap> </mapper>
8.5.测试
map<string, integer> parammap = new hashmap<>(); parammap.put("sex_id", 0); session.selectone(statement, parammap); integer usercount = parammap.get("user_count"); system.out.println(usercount);
九、mybatis缓存
9.1.理解mybatis缓存
正如大多数持久层框架一样,mybatis 同样提供了一级缓存和二级缓存的支持
1.一级缓存: 基于perpetualcache 的 hashmap本地缓存,其存储作用域为 session,当 session flush 或 close 之后,该session中的所有 cache 就将清空。
2. 二级缓存与一级缓存其机制相同,默认也是采用 perpetualcache,hashmap存储,不同在于其存储作用域为 mapper(namespace),并且可自定义存储源,如 ehcache。
3. 对于缓存数据更新机制,当某一个作用域(一级缓存session/二级缓存namespaces)的进行了 c/u/d 操作后,默认该作用域下所有 select 中的缓存将被clear。
9.2.mybatis一级缓存
9.2.1.根据任务查询
根据id查询对应的用户记录对象。
9.2.2.准备数据库表和数据
create table c_user( id int primary key auto_increment, name varchar(20), age int ); insert into c_user(name, age) values('tom', 12); insert into c_user(name, age) values('jack', 11);
9.2.3.创建表的实体类
public class user implements serializable{ private int id; private string name; private int age;
9.2.4.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.atguigu.mybatis.test8.usermapper"> <select id="getuser" parametertype="int" resulttype="_cuser"> select * from c_user where id=#{id} </select> <update id="updateuser" parametertype="_cuser"> update c_user set name=#{name}, age=#{age} where id=#{id} </update> </mapper>
9.2.5.测试
/* * 一级缓存: 也就session级的缓存(默认开启) */ @test public void testcache1() { sqlsession session = mybatisutils.getsession(); string statement = "com.atguigu.mybatis.test8.usermapper.getuser"; user user = session.selectone(statement, 1); system.out.println(user); /* * 一级缓存默认就会被使用 */ /* user = session.selectone(statement, 1); system.out.println(user); */ /* 1. 必须是同一个session,如果session对象已经close()过了就不可能用了 */ /* session = mybatisutils.getsession(); user = session.selectone(statement, 1); system.out.println(user); */ /* 2. 查询条件是一样的 */ /* user = session.selectone(statement, 2); system.out.println(user); */ /* 3. 没有执行过session.clearcache()清理缓存 */ /* session.clearcache(); user = session.selectone(statement, 2); system.out.println(user); */ /* 4. 没有执行过增删改的操作(这些操作都会清理缓存) */ /* session.update("com.atguigu.mybatis.test8.usermapper.updateuser", new user(2, "user", 23)); user = session.selectone(statement, 2); system.out.println(user); */ }
9.3.mybatis二级缓存
9.3.1.添加一个<cache>在usermapper.xml中
<mapper namespace="com.atguigu.mybatis.test8.usermapper"> <cache/>
9.3.2.测试
/* * 测试二级缓存 */ @test public void testcache2() { string statement = "com.atguigu.mybatis.test8.usermapper.getuser"; sqlsession session = mybatisutils.getsession(); user user = session.selectone(statement, 1); session.commit(); system.out.println("user="+user); sqlsession session2 = mybatisutils.getsession(); user = session2.selectone(statement, 1); session.commit(); system.out.println("user2="+user); }
9.3.3.补充说明
1. 映射语句文件中的所有select语句将会被缓存。
2. 映射语句文件中的所有insert,update和delete语句会刷新缓存。
3. 缓存会使用least recently used(lru,最近最少使用的)算法来收回。
4. 缓存会根据指定的时间间隔来刷新。
5. 缓存会存储1024个对象
<cache eviction="fifo" //回收策略为先进先出 flushinterval="60000" //自动刷新时间60s size="512" //最多缓存512个引用对象 readonly="true"/> //只读
十、spring集成mybatis
10.1.添加jar
【mybatis】
mybatis-3.2.0.jar
mybatis-spring-1.1.1.jar
log4j-1.2.17.jar
【spring】
spring-aop-3.2.0.release.jar
spring-beans-3.2.0.release.jar
spring-context-3.2.0.release.jar
spring-core-3.2.0.release.jar
spring-expression-3.2.0.release.jar
spring-jdbc-3.2.0.release.jar
spring-test-3.2.4.release.jar
spring-tx-3.2.0.release.jar
aopalliance-1.0.jar
cglib-nodep-2.2.3.jar
commons-logging-1.1.1.jar
【mysql驱动包】
mysql-connector-java-5.0.4-bin.jar
10.2.数据库表
create table s_user( user_id int auto_increment primary key, user_name varchar(30), user_birthday date, user_salary double )
10.3.实体类:user
public class user { private int id; private string name; private date birthday; private double salary; //set,get方法 }
10.4.dao接口: usermapper (xxxmapper)
public interface usermapper { void save(user user); void update(user user); void delete(int id); user findbyid(int id); list<user> findall(); }
10.5.sql映射文件: 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.atguigu.mybatis.test9.usermapper"> <resultmap type="user" id="userresult"> <result column="user_id" property="id"/> <result column="user_name" property="name"/> <result column="user_birthday" property="birthday"/> <result column="user_salary" property="salary"/> </resultmap> <!-- 取得插入数据后的id --> <insert id="save" keycolumn="user_id" keyproperty="id" usegeneratedkeys="true"> insert into s_user(user_name,user_birthday,user_salary) values(#{name},#{birthday},#{salary}) </insert> <update id="update"> update s_user set user_name = #{name}, user_birthday = #{birthday}, user_salary = #{salary} where user_id = #{id} </update> <delete id="delete"> delete from s_user where user_id = #{id} </delete> <select id="findbyid" resultmap="userresult"> select * from s_user where user_id = #{id} </select> <select id="findall" resultmap="userresult"> select * from s_user </select> </mapper>
10.6.spring的配置文件: beans.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 1. 数据源 : drivermanagerdatasource --> <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="com.mysql.jdbc.driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!-- 2. mybatis的sqlsession的工厂: sqlsessionfactorybean datasource / typealiasespackage --> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> <property name="datasource" ref="datasource"/> <property name="typealiasespackage" value="com.atuigu.spring_mybatis2.domain"/> </bean> <!-- 3. mybatis自动扫描加载sql映射文件 : mapperscannerconfigurer sqlsessionfactory / basepackage --> <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"> <property name="basepackage" value="com.atuigu.spring_mybatis2.mapper"/> <property name="sqlsessionfactory" ref="sqlsessionfactory"/> </bean> <!-- 4. 事务管理 : datasourcetransactionmanager --> <bean id="txmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"> <property name="datasource" ref="datasource"/> </bean> <!-- 5. 使用声明式事务 --> <tx:annotation-driven transaction-manager="txmanager" /> </beans>
10.7.mybatis的配置文件: mybatis-config.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> <!-- spring整合mybatis后,这个配置文件基本可以不要了--> <!-- 设置外部配置文件 --> <!-- 设置类别名 --> <!-- 设置数据库连接环境 --> <!-- 映射文件 --> </configuration>
10.8.测试
@runwith(springjunit4classrunner.class) //使用springtest测试框架 @contextconfiguration("/beans.xml") //加载配置 public class smtest { @autowired //注入 private usermapper usermapper; @test public void save() { user user = new user(); user.setbirthday(new date()); user.setname("marry"); user.setsalary(300); usermapper.save(user); system.out.println(user.getid()); } @test public void update() { user user = usermapper.findbyid(2); user.setsalary(2000); usermapper.update(user); } @test public void delete() { usermapper.delete(3); } @test public void findbyid() { user user = usermapper.findbyid(1); system.out.println(user); } @test public void findall() { list<user> users = usermapper.findall(); system.out.println(users); } }
以上所述是小编给大家介绍的mybatis快速入门(简明浅析易懂),希望对大家有所帮助