Mybatis--环境搭建及CRUD

2019-04-01  本文已影响0人  Unclezs

一.环境搭建

1.主要配置,数据库连接信息及映射类

db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test?characterEncoding=utf8
username=root
password=123
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>
    <!--加载数据库连接配置-->
    <properties resource="db.properties"/>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="jdbc"></transactionManager>
            <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>
    <mappers>
        <mapper resource="com/unclezs/dao/IUserDao.xml"></mapper>
    </mappers>
</configuration>

2.编写映射类IUserDao.java

public interface IUserDao { //todo}

3.映射类的配置文件

<?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.unclezs.dao.IUserDao">
    <!-- todo -->
</mapper>

4.配置log4j

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug,CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL,CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

二、CRUD

1.映射文件

<?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.unclezs.dao.IUserDao">
    <select id="findAll" resultType="com.unclezs.domain.User">
        select * from user
    </select>
    <select id="findUserById" resultType="com.unclezs.domain.User" parameterType="int">
        select * from user where id=#{id}
    </select>
    <insert id="addUser" parameterType="com.unclezs.domain.User">
    <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
        select last_insert_id();
    </selectKey>
        insert into USER(username,birthday,address,sex) values (#{username},#{birthday},#{address},#{sex})
    </insert>
    <update id="updateUser" parameterType="com.unclezs.domain.User">
        update user set username=#{username} where id=#{id}
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
</mapper>

2.映射类

package com.unclezs.dao;

import com.unclezs.domain.User;

import java.util.List;

/**
 * @Author Unclezs.com
 * @Date 20:05 2019.03.24
 **/
public interface IUserDao {
    /**
     * 查找所有用户
     * @return
     */
    public List<User> findAll();
    /**
     * 根据查找一个用户
     * @return
     */
    public User findUserById(int id);

    /**
     * 添加用户
     * @param user
     */
    public void addUser(User user);

    /**
     * 更新用户
     * @param user
     */
    public void updateUser(User user);

    /**
     * 删除用户
     * @param
     */
    public void deleteUser(int id);

}

3.实体类

package com.unclezs.domain;

import java.sql.Date;

/**
 * @Author Unclezs.com
 * @Date 20:05 2019.03.24
 **/
public class User {
    private int id;
    private String username;
    private Date birthday;
    private String address;
    private String sex;

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

    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 getAddress() {
        return address;
    }

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

    public String getSex() {
        return sex;
    }

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

4.测试类

public class AppTest {
    private InputStream in;
    private SqlSessionFactory sessionFactory;
    private SqlSession session;
    private IUserDao userDao;
    @Before
    public void init() throws Exception {
        //1.加载配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建session工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        sessionFactory = builder.build(in);
        //3.获取会话
        session = sessionFactory.openSession(true);
        userDao = session.getMapper(IUserDao.class);
    }

    @Test
    public void testFindAll() {
        System.out.println(userDao.findAll());

    }
    @Test
    public void testAddUser(){
        User user=new User();
        user.setAddress("重庆");
        user.setUsername("uncle");
        user.setSex("男");
        user.setBirthday(new Date(System.currentTimeMillis()));
        System.out.println(user);
        userDao.addUser(user);
//        session.commit();
        System.out.println(user);
    }
    @Test
    public void TestUpdateUser(){
        User user = userDao.findUserById(54);
        user.setUsername("uncle");
        userDao.updateUser(user);
    }
    @Test
    public void testDeleteUser(){
        userDao.deleteUser(45);
    }
    @After
    public void destory() throws IOException {
        session.close();
        in.close();
    }
}
上一篇下一篇

猜你喜欢

热点阅读