java-mybatis配置文件方式

image

1、添加依赖

<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.12</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.15</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>provided</scope>
        </dependency>
        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、添加配置logback的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE :表示当前的日志信息是可以输出到控制台的。
    -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%level]  %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="cn.tjhis" level="DEBUG" additivity="false">
        <appender-ref ref="Console"/>
    </logger>


    <!--

      level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
     , 默认debug
      <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
      -->
    <root level="DEBUG">
        <appender-ref ref="Console"/>
    </root>
</configuration>

3、添加mybatis配置文件

<?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>

    <typeAliases>
        <package name="cn.tjhis.pojo"/>
    </typeAliases>
    
    <!--
    environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
    -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/wangdb?useUnicode=true;characterEncoding=utf8;serverTimezone=GMT;useSSL=false;useServerPrepStmts=true"/>
                <property name="username" value="root"/>
                <property name="password" value="Tjwang99123@"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql映射文件-->
<!--        <mapper resource="mapper/UserMapper.xml"/>-->

        <!--Mapper代理方式-->
        <package name="cn.tjhis.mapper"/>

    </mappers>


</configuration>

4、添加pojo

@Data
public class User {
  private Integer id;
  private String userName;
  private String password;
  private LocalDate birth;
}

5、添加mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.tjhis.mapper.UserMapper">
    <resultMap id="user" type="cn.tjhis.pojo.User">
        <result property="userName" column="user_name"/>
    </resultMap>
    <insert id="insertUser">
        insert into user ( user_name, password, birth)
        values (#{userName},#{password},#{birth})
    </insert>
    <update id="updateUserById">
        update user set user_name=#{userName},
        password=#{password},
        birth=#{birth}
        where id = #{id}
    </update>
    <delete id="deleteUserById">
        delete from user where id = #{id}
    </delete>
    <select id="selectUserById" resultMap="user">
        select * from user where id = #{id}
    </select>
    <select id="selectAll" resultMap="user">
        select * from user
    </select>

</mapper>

6、添加mapper.java

public interface UserMapper {
	List<User> selectAll();
	User selectUserById(int id);
	boolean deleteUserById(int id);
	boolean updateUserById(User user);

	boolean insertUser(User user);

}

7、测试

public class TestDemo {
  @Test
  public void testSelectAll() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    try (SqlSession session = sqlSessionFactory.openSession()) {
      UserMapper mapper = session.getMapper(UserMapper.class);
      List<User> userList = mapper.selectAll();
      System.out.println(userList);
    }
  }
  @Test
  public void testSelect() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    try (SqlSession session = sqlSessionFactory.openSession()) {
      UserMapper mapper = session.getMapper(UserMapper.class);
      User user = mapper.selectUserById(5);
      System.out.println(user);
    }
  }
  @Test
  public void testUpdate() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    try (SqlSession session = sqlSessionFactory.openSession(true)) {
      UserMapper mapper = session.getMapper(UserMapper.class);
      User user = mapper.selectUserById(7);
      user.setUserName("孙悟空");
      user.setPassword("123");
      user.setBirth(LocalDate.of(1990, 3, 21));
      boolean updateUser = mapper.updateUserById(user);
      System.out.println(updateUser);
    }
  }

  @Test
  public void testInsert() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    try (SqlSession session = sqlSessionFactory.openSession(true)) {
      UserMapper mapper = session.getMapper(UserMapper.class);
      User user = new User();
      user.setUserName("张三");
      user.setPassword("123");
      user.setBirth(LocalDate.of(1985, 7, 10));
      boolean insertUser = mapper.insertUser(user);
      System.out.println(insertUser);
    }
  }
  @Test
  public void testDelete() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // openSession 参数传true 开启事务
    try (SqlSession session = sqlSessionFactory.openSession(true)) {
      UserMapper mapper = session.getMapper(UserMapper.class);
      boolean deleteUser = mapper.deleteUserById(19);
      System.out.println(deleteUser);
    }
  }
}

批量删除

  • mapper.xml
<delete id="deleteUserByIds">
        delete from user where id in
        <foreach collection="ids" item ="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
  • mapper
boolean deleteUserByIds(@Param("ids") int[] ids);
  • 测试
 @Test
  public void testDeleteByIds() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // openSession 参数传true 开启事务
    try (SqlSession session = sqlSessionFactory.openSession(true)) {
      UserMapper mapper = session.getMapper(UserMapper.class);
      int[] ids = {5,7,8,9};
      boolean deleteUser = mapper.deleteUserByIds(ids);
      System.out.println(deleteUser);
    }
posted @ 2023-03-03 14:19  his365  阅读(62)  评论(0编辑  收藏  举报