美文网首页
Mybatis--环境搭建及CRUD

Mybatis--环境搭建及CRUD

作者: Unclezs | 来源:发表于2019-04-01 14:05 被阅读0次

一.环境搭建

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();
    }
}

相关文章

  • Mybatis--环境搭建及CRUD

    一.环境搭建 1.主要配置,数据库连接信息及映射类 db.properties SqlMapConfig.xml ...

  • 第一个MyBatis程序

    思路:搭建环境---导入MyBatis--编写代码---测试! 一、搭建环境 1、搭建数据库环境: engine=...

  • 2019-08-18 项目实践

    mybatis mybatis 环境搭建 mybatis 自己实现类 单表的crud 返回值 和 参数 dao编写...

  • MyBatis-Plus的CRUD及其扩展

    测试环境在上一篇MyBatis-Plus概述中搭建完成! Mapper CRUD 接口 Insert Delete...

  • Mybatis知识day02 CRUD操作

    一、基于代理 Dao 实现 CRUD 操作 1.1mybatis 环境搭建步骤: 第一步:创建 maven 工程 ...

  • fabric1.2网络环境启动过程详解

    fabric运行机制及环境搭建 fabric运行机制及环境搭建环境依赖基于docker镜像的fabric1.2开发...

  • mall整合SpringBoot+MyBatis搭建基本骨架

    本文主要讲解mall整合SpringBoot+MyBatis搭建基本骨架,以商品品牌为例实现基本的CRUD操作及通...

  • ELK 搭建及实战

    ELK 搭建及实战 JDK1.8环境搭建和Kibana实战部署 ELK介绍和JDK1.8环境搭建 实战环境 Cen...

  • test

    破碎可视化环境搭建及部署文档 软交换机上环境搭建及程序部署 搭建前准备 debian8 系统盘、 JDK8 压缩包...

  • cesium编程入门(二)环境搭建

    环境搭建 环境搭建 编译 node 安装 Node.js安装包及源码下载地址为:https://nodejs.or...

网友评论

      本文标题:Mybatis--环境搭建及CRUD

      本文链接:https://www.haomeiwen.com/subject/iskvbqtx.html