`

myBatis入门实例

 
阅读更多
1、创建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>
    <properties resource="jdbc.properties"/>
    <typeAliases>
        <package name="itat.zttc.shop.model"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中 -->
    <mappers>
    <mapper resource="itat/zttc/shop/model/User.xml"/>
    </mappers>
</configuration>

jdbc.properties
username=root
password=hello
url=jdbc:mysql://localhost:3306/itat_shop
driver=com.mysql.jdbc.Driver

2、根据数据表创建相应的实体类
数据表

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(32) NOT NULL,
  `nickname` varchar(30) NOT NULL,
  `type` int(2) unsigned NOT NULL,
  PRIMARY KEY (`id`)
)


public class User 
    private int id;
    private String username;
    private String password;
    private String nickname;
    private int type;
    private List<Address> addresses;

3、创建mapper文件完成对实体类的映射,该文件同样是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="itat.zttc.shop.model.User">
<!-- <mapper namespace="itat.zttc.shop.mapper.UserMapper"> -->
    <insert id="add" parameterType="User">
        insert into user (username,password,nickname,type)
            value(#{username},#{password},#{nickname},#{type})
    </insert>
    
    <update id="update" parameterType="User">
        update user set password=#{password},nickname=#{nickname},type=#{type} where id=#{id}
    </update>
    
    <delete id="delete" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
    <select id="load" parameterType="int" resultType="User">
        select * from user where id=#{id}
    </select>
    
    <select id="list" resultType="User">
        select * from user
    </select>
</mapper>

4、创建SQlSession,并且通过SqlSession完成对数据库的操作
package itat.zttc.shop.util;
import java.io.IOException;
public class MyBatisUtil {
    private static SqlSessionFactory factory;
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static SqlSession createSession() {
        return factory.openSession();
    }
    
    public static void closeSession(SqlSession session) {
        if(session!=null) session.close();
    }
}

5、最佳实践
   1、创建相应的MyBatisUtil完成对Session的获取
   2、不使用annotation完成sql的映射
import itat.zttc.shop.model.User;
public class TestMyBatis {
    @Test
    public void testDelete() {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory f = new SqlSessionFactoryBuilder().build(is);
            SqlSession session = f.openSession();
            session.delete(User.class.getName()+".delete",105);
            session.commit();
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void testAdd() {
        SqlSession session = null;
        try {
            session = MyBatisUtil.createSession();
            User u = new User();
            u.setNickname("孙悟空");
            u.setPassword("123");
            u.setType(1);
            u.setUsername("wukong");
            session.insert(User.class.getName()+".add", u);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        } finally {
            MyBatisUtil.closeSession(session);
        }
    }
    
    @Test
    public void testLoad() {
        SqlSession session = null;
        try{
            session = MyBatisUtil.createSession();
            User u = (User)session.selectOne(User.class.getName()+".load", 1);
            System.out.println(u.getNickname());
        } finally {
            MyBatisUtil.closeSession(session);
        }
    }
    
    @Test
    public void testList() {
        SqlSession session = null;
        try{
            session = MyBatisUtil.createSession();
            List<User> us = session.selectList(User.class.getName()+".list", null);
            System.out.println(us.size());
        } finally {
            MyBatisUtil.closeSession(session);
        }
    }
    
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics