Mybatis Dao开发的两种方式(一)

 原始Dao的开发方式:

1、创建数据库配置文件db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名称
jdbc.name=数据库登录用户名
jdbc.pwd=数据库登录密码

2、创建配置文件SqlMapConfig.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>
    <!--
    加载属性文件
    resource:属性文件的相对路径
    url:属性文件的绝对路径
 -->
<properties resource="config/db.properties">
    <!--
        配置一些属性
        name:属性的名称
        value:属性的值
    -->
    <!--<property name="" value="" /> -->
</properties>
    <!--
        环境配置
        在和Spring整合后改配置将废除
    -->
    <environments default="development">

        <environment id="development">
            <!--使用JDBC的事务管理,事务管理交给Mybatis-->
            <transactionManager type="JDBC"></transactionManager>
            <!--数据库连接池,有Mybatis管理-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.name}" />
                <property name="password" value="${jdbc.pwd}" />
            </dataSource>
        </environment>
    </environments>
</configuration>

3、创建PO类

public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

4、创建映射文件

<?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:命名空间,对SQL进行分类化的管理,进行sql隔离
-->
<mapper namespace="test">
    <!--
        查询sql语句配置使用select标签
        id:该语句的唯一标识,通常称为statement的id
        parameterType:输入参数的类型
        resultType:返回数据的类型,指定为Java的po类型,则将查询出来的单条记录映射为po对象。
    -->
    <select id="findUserById" parameterType="int" resultType="com.jack.po.User" >
        <!--
            要执行的sql语句
            #{} :表示一个占位符
            #{value} :value表示接受的参数,名称为value,如果参数是简单类型,则名称可以随意起。
        -->
          SELECT * FROM user WHERE  id=#{value}
    </select>

    <select id="findUserByName" parameterType="String" resultType="com.jack.po.User">
        SELECT * FROM user WHERE username LIKE '%${value}%'
    </select>

    <insert id="insertUserInfo" parameterType="com.jack.po.User">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT INTO user(username,birthday,sex,address) VALUE (#{username},#{birthday},#{sex},#{address})
    </insert>

    <update id="updateUserInfo" parameterType="com.jack.po.User" >
        UPDATE user set birthday=#{birthday},sex=#{sex},address=#{address} WHERE  id=#{id}
    </update>

    <update id="deleteUserInfo" parameterType="int" >
        DELETE FROM user WHERE  id=#{value}
    </update>
</mapper>

5、在SqlMapConfig.xml中引入该映射文件

  <!--引入mapper-->
    <mappers>
        <mapper resource="config/sqlmap/userMapper.xml" />
    </mappers>

6、编写Dao接口文件

public interface UserServiceI{

    //根据id查询用户的接口
    public User findUserById(int id) throws Exception;
    //根据用户名查询用户
    public List<User> findUserByName(String name) throws Exception;
    //插入用户信息
    public int insertUserInfo(User user) throws Exception;
    //根据id更新用户信息
    public void updateUserInfo(User user) throws Exception;
    //根据id删除用户信息
    public void deleteUserInfo(int id) throws Exception;
}

7、编写接口实现类

public class UserServiceImpl  implements UserServiceI{

    private SqlSessionFactory sessionFactory;

    public UserServiceImpl(SqlSessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }
    @Override
    public User findUserById(int id) throws Exception {
        SqlSession session = sessionFactory.openSession();
        User user =  session.selectOne("findUserById",id);
        return user;
    }

    @Override
    public List<User> findUserByName(String name) throws Exception {
        SqlSession session = sessionFactory.openSession();
        List<User> list = session.selectList("findUserByName",name);
        return list;
    }

    @Override
    public int insertUserInfo(User user) throws Exception {
        SqlSession session = sessionFactory.openSession();
        session.insert("insertUserInfo",user);
        session.commit();
        return user.getId();

    }

    @Override
    public void updateUserInfo(User user) throws Exception {
        SqlSession session = sessionFactory.openSession();
        session.insert("updateUserInfo",user);
        session.commit();
    }

    @Override
    public void deleteUserInfo(int id) throws Exception {
        SqlSession session = sessionFactory.openSession();
        session.delete("deleteUserInfo",id);
        session.commit();
    }
}

8、编写测试代码进行测试

public class UserTest {

    private SqlSessionFactory sessionFactory;
    @Before
    public void setUp() throws  Exception{
        String resource = "config/SqlMapConfig.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        sessionFactory = new SqlSessionFactoryBuilder().build(in);
        }


    @Test
public void findUserById(){
    UserServiceI userService = new UserServiceImpl(sessionFactory);
    try {
        User user =  userService.findUserById(10);
        System.out.println(user);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {

    }
}

    @Test
    public void findUserByName(){
        UserServiceI userService = new UserServiceImpl(sessionFactory);
        try {
           List<User> list  =  userService.findUserByName("小明");
            for (User user:list) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }

    @Test
    public void insertUserInfo(){
        UserServiceI userService = new UserServiceImpl(sessionFactory);
        try {
            User user = new User();
            user.setId(26);
            user.setBirthday(new Date());
            user.setSex("1");
            user.setAddress("甘肃天水");
            userService.updateUserInfo(user);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }

    public void updateUserInfo(){
        UserServiceI userService = new UserServiceImpl(sessionFactory);
        try {
            User user = new User();
            user.setUsername("东方不败");
            user.setBirthday(new Date());
            user.setSex("0");
            user.setAddress("黑木崖");
            int id =userService.insertUserInfo(user);
            System.out.println(id);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }

    @Test
    public void deleteUserInfo(){
        UserServiceI userService = new UserServiceImpl(sessionFactory);
        try {
            userService.deleteUserInfo(28);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }
}
posted @ 2017-07-27 08:23  一条路上的咸鱼  阅读(590)  评论(0编辑  收藏  举报