MyBatis-xml版本

MyBatis 是一款优秀的持久层框架
MyBatis中文网https://mybatis.net.cn/


添加依赖

<dependencies>
    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.47version>
    dependency>
    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.2version>
    dependency>
    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
    dependency>
dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/javadirectory>
            <includes>
                <include>**/*.propertiesinclude>
                <include>**/*.xmlinclude>
            includes>
            <filtering>truefiltering>
        resource>
        <resource>
            <directory>src/main/resourcesdirectory>
            <includes>
                <include>**/*.propertiesinclude>
                <include>**/*.xmlinclude>
            includes>
            <filtering>truefiltering>
        resource>
    resources>
build>

resources目录下编写配置文件

  • db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL&useUnicode=true&charsetEncoding=UTF-8
username=root
password=123
  • log4j.properties
# 输出DEBUG级别的日志到console和file
log4j.rootLogger=DEBUG,console,file
#输出到控制台的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold = DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
# log4j.appender.console.layout.ConversionPattern = [%c]-%m%n
log4j.appender.console.layout.ConversionPattern=%5p [%t] - %m%n
#输出到文件的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
# 不追加写入:log4j.appender.file.Append = false
# 输出位置
log4j.appender.file.File = ./log/log.log
# 文件最大容量,满了会生成新的文件
log4j.appender.file.MaxFileSize = 10mb
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = [%p][%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis = DEBUG
log4j.logger.java.sql = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.ResultSet = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
  • mybatis-config.xml

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
    
    <properties resource="db.properties">
        
        <property name="addr" value="bj"/>
    properties>
    <settings>
        

        <setting name="logImpl" value="LOG4J"/>
        
        <setting name="cacheEnabled" value="true"/>
    settings>
    
    <typeAliases>
        
        <typeAlias type="org.example.pojo.User" alias="User"/>
        
        <package name="org.example.pojo"/>
    typeAliases>
    
    <environments default="prd">
        <environment id="dev">
            
            <transactionManager type="JDBC">transactionManager>
            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL&useUnicode=true&charsetEncoding=UTF-8"/>
            dataSource>
        environment>
        <environment id="prd">
            <transactionManager type="JDBC">transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
                <property name="url" value="${url}"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="org/example/dao/UserMapper.xml"/>
    mappers>
configuration>

实体类

//@Alias("user")
public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;
    // getter、setter、tostring、有参构造、无参构造
}

mapper接口

public interface UserMapper {
    // xml实现
    List<User> getUsers();
    // 多参数情况下用注解@Param("占位名")声明
    User getUser(@Param("user_name") String username,@Param("pass_word") String password);
    User getUserById(Integer id);
    int insertUser(User user);
    int insertUserBatch(@Param("userList") List<User> userList);
    // 常用map做参数
    int insertUserAsMap(Map<String,Object> map);
    int updateUserById(User user);
    int deleteUserById(Integer id);
    int deleteUserByIds(Integer[] id);

    // 注解实现
    @Select("select * from user")
    List<User> getUsers2();
}

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.example.dao.UserMapper">
    
    
    <cache/>
    <resultMap id="userMap" type="org.example.pojo.User">
        
        <id column="id" property="id"/>
        
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        

        
        
    resultMap>
    <select id="getUsers" resultMap="userMap">
        select * from user
        
        
    select>
    <select id="getUser" resultMap="userMap">
        select * from user
        <where>
            <if test="user_name != null and user_name != ''">
                and username like concat('%',#{user_name},'%')
            if>
            <if test="pass_word != null and pass_word != ''">
                and password = #{pass_word}
            if>
            
            
        where>
    select>
    <select id="getUserById" parameterType="java.lang.Integer" resultType="org.example.pojo.User">
        select * from user where id = #{id}
    select>
    
    <insert id="insertUser" keyProperty="id" useGeneratedKeys="true">
        insert into user (id,username,password) values(#{id},#{username},#{password})
    insert>
    
    <insert id="insertUserBatch">
        insert into user (id,username,password) values
        <foreach collection="userList" item="user" separator=",">
            (#{user.id},#{user.username},#{user.password})
        foreach>
    insert>
    
    <insert id="insertUserAsMap" parameterType="java.util.Map">
        insert into user (username,password) values(#{name},#{pwd})
    insert>
    <update id="updateUserById" parameterType="org.example.pojo.User">
        update user
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            if>
            <if test="password != null and password != ''">
                password = #{password},
            if>
        set>
        <where>
            <if test="id != null">
                and id = #{id}
            if>
        where>
    update>
    <delete id="deleteUserById" parameterType="java.lang.Integer">
        delete from user where id = #{id}
    delete>
    <delete id="deleteUserByIds">
        delete from user where id in
        
        <foreach collection="array" item="id" separator="," open="(" close=")">
            #{id}
        foreach>
    delete>
mapper>

测试类

public class Test01 {
    private SqlSession sqlSession;
    @Before
    public void before(){
        SqlSessionFactory sqlSessionFactory;
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        sqlSession =  sqlSessionFactory.openSession();
        System.out.println("@Before在测试方法执行前执行,可以在此处获取sqlSession");
    }
    @After
    public void after(){
        // DML语句需要提交事务
        sqlSession.commit();
        sqlSession.close();
        System.out.println("@After在测试方法完成后执行,可以在此处提交事务,关闭资源");
    }
    @Test
    public void test01() {
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//        System.out.println(userMapper.getUserById(-3));
//        User user = new User(null,"zhaoliu", "12345");
//        System.out.println(userMapper.insertUser(user));
//        System.out.println(user.getId());
//        List userList = new ArrayList<>();
//        userList.add(new User(6,"66","666"));
//        userList.add(new User(7,"77","777"));
//        System.out.println(userMapper.insertUserBatch(userList));
//        System.out.println(userMapper.updateUserById(new User(5, "zhao", "12345")));
//        System.out.println(userMapper.deleteUserById(-4));
//        System.out.println(userMapper.deleteUserByIds(new Integer[]{6,7}));
//        Map map = new HashMap();
//        map.put("name","chenqi");
//        map.put("pwd",1234);
//        System.out.println(userMapper.insertUserAsMap(map));
//        System.out.println(userMapper.getUser("lisi","12345"));
//        System.out.println(userMapper.getUsers());
        System.out.println(userMapper.getUsers2());
    }
}

你可能感兴趣的:(java)