首页 > 代码库 > mybatis入门例子

mybatis入门例子

开发步骤:

1.创建java工程
2.加入jar包(依赖包、驱动包)
3.创建sqlMapConfig.xml
4.创建数据库,数据库表USER_C,插入测试记录
5.创建PO对象 user.java
6.创建映射文件 User.xml
7.创建测试类

占位符:

iBatis  #id#

myBatis  #{id}

1、创建web工程

2、导入jar包:

mybatis-3.2.2.jar
 
asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
log4j-1.2.17.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
 

3、配置文件 sqlMapConfig.xml :

事务:JDBC/MANAGED

数据源:UNPOOLED/POOLED/JNDI

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6     <environments default="development"> 7         <environment id="development"> 8             <transactionManager type="JDBC"/> 9             <dataSource type="POOLED">10                 <property name="driver" value="com.mysql.jdbc.Driver"/>11                 <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=UTF-8"/>12                 <property name="username" value="root"/>13                 <property name="password" value="root"/>14             </dataSource>15         </environment>16     </environments>17 18     <mappers>19         <mapper resource="cn/itcast/mybatis/domain/User.xml"/>20     </mappers>21 </configuration>

4.创建数据库

创建mybatisdb数据库
创建User表

 

create table USER_C

(

   ID                   varchar(40) not null,

   NAME                 varchar(30),

   AGE                  int,

   ADDRESS              varchar(200),

   primary key (ID)

);

insert  into `user_c`(`id`,`name`,`age`,`address`)

values (‘1‘,‘夏言‘,73,‘桂州村‘),

(‘2‘,‘严嵩‘,87,‘分宜县城介桥村‘),

(‘3‘,‘徐阶‘,80,‘明松江府华亭县‘),

(‘4‘,‘高拱‘,66,‘河南省新郑市高老庄村‘),

(‘5‘,‘张居正‘,58,‘江陵‘);

5、映射文件 cn.itcast.mybatis.domain.User.xml :

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <!--                 命名空间用于查找 --> 6 <mapper namespace="cn.itcast.mybatis"> 7      8 <!--     替代,语句中的内容,简写 --> 9     <sql id="cols">10          id,name,age,address       11     </sql>12 <!--     查询所有记录 -->13     <select id="listAll" resultType="cn.itcast.domain.User">14         select <include refid="cols"/> from   user_c      15     </select>16 17 <!--     查询一个用户 -->                            <!--  别名替代,简写-->18     <select id="getOne" parameterType="string" resultType="aliasesUser">19         select <include refid="cols"/> from   user_c  where id= #{id}    20     </select>21     22 <!--     插入一个用户 -->23     <insert id="insertOne" parameterType="cn.itcast.domain.User" >24         insert into user_c( <include refid="cols"/> ) values (#{id},#{name},#{age},#{address})    25     </insert>26     27 <!--     更新一个用户 -->28     <insert id="updateOne" parameterType="cn.itcast.domain.User" >29         update user_c set name=#{name},age=#{age},address=#{address} where id=#{id}    30     </insert>31     32     <!--     删除一个用户 -->33     <update id="deleteOne" parameterType="cn.itcast.domain.User" >34         delete from user_c where id= #{id}   35     </update>36 </mapper>

6、PO对象 User.java :

 1 package cn.itcast.domain; 2  3 public class User { 4     private String id; 5     private String name; 6     private Integer age; 7     private String address; 8     public String getAddress() { 9         return address;10     }11     public void setAddress(String address) {12         this.address = address;13     }14     public String getId() {15         return id;16     }17     public void setId(String id) {18         this.id = id;19     }20     public String getName() {21         return name;22     }23     public void setName(String name) {24         this.name = name;25     }26     public Integer getAge() {27         return age;28     }29     public void setAge(Integer age) {30         this.age = age;31     }32     @Override33     public String toString() {34         return "User [id=" + id + ", name=" + name + ", age=" + age + "]";35     }36     37 }

7、测试类:

 1 package cn.itcast.test; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6 import java.util.UUID; 7  8 import org.apache.ibatis.io.Resources; 9 import org.apache.ibatis.session.SqlSession;10 import org.apache.ibatis.session.SqlSessionFactory;11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;12 import org.junit.Before;13 import org.junit.Test;14 15 import cn.itcast.domain.User;16 17 public class TestMybatis {18 19     SqlSessionFactory sqlSessionFactory;20     21     @Before22     public void initFactory() throws IOException23     {24         String resource = "sqlMapConfig.xml";25 26         InputStream inputStream = Resources.getResourceAsStream(resource);27 28         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);29     }30     31     @Test32     public  void testListAll()33     {34         SqlSession session=sqlSessionFactory.openSession();35         List<User> users=session.selectList("cn.itcast.mybatis.listAll");36         System.out.println(users.size());37     }38     @Test39     public void testQueryOne()40     {41         SqlSession session=sqlSessionFactory.openSession();42         User user=session.selectOne("cn.itcast.mybatis.getOne", 1);43         System.out.println(user);44     }45     //事务需要程序员处理46     @Test47     public void testInsertOne()48     {49         User u=new User();50         u.setId(UUID.randomUUID().toString());51         u.setName("sbsbb");52         u.setAge(18);53         u.setAddress("china");54         SqlSession session=sqlSessionFactory.openSession();55         int count=session.insert("cn.itcast.mybatis.insertOne", u);56         session.commit();57         System.out.println(count);58     }59     60     @Test61     public void testUpdateOne()62     {63         SqlSession session=sqlSessionFactory.openSession();64         User u=new User();65         //u=session.selectOne("cn.itcast.mybatis.getOne", "2");66         u.setId("2");67         u.setName("clclclclclcfei");68         u.setAge(100);69         u.setAddress("USA");70         int count=session.update("cn.itcast.mybatis.updateOne", u);71         session.commit();72         System.out.println(count);73     }74     @Test75     public void testDeleteOne()76     {77         SqlSession session=sqlSessionFactory.openSession();78         User u=new User();79         u.setId("2");80         int count=session.delete("cn.itcast.mybatis.deleteOne", u);81         session.commit();82         System.out.println(count);83     }84     85     86     87 }