首页 > 编程语言 >java-mybatis

java-mybatis

时间:2023-03-03 14:23:08浏览次数:38  
标签:mapper java UserMapper session user mybatis resource

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(1979, 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,java,UserMapper,session,user,mybatis,resource
From: https://www.cnblogs.com/his365/p/17175478.html

相关文章

  • android studio 打包发布 Cause: failed to decrypt safe contents entry: javax.cryp
    androidstudio打包发布错误:Cause:failedtodecryptsafecontentsentry:javax.crypto.BadPaddingException:Givenfinalblocknotproperlypadded.Suchissues......
  • 如何在 JavaScript 中使用媒体查询
    前言说起媒体查询想必大家最先想到的都是CSS中@media,没错,这是我们最常用的媒体查询方法,主要用来为我们的网站做适配处理。比如:h1{font-size:2rem;color:green;......
  • springboot整合mybatis
    1,引入依赖<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version><scope>runtime</scope></depend......
  • JavaScript模块化理解-CommonJS、AMD、CMD、UMD、ES6
    参考:JavaScript模块化-CommonJS、AMD、CMD、UMD、ES6前端模块化——彻底搞懂AMD、CMD、ESM和CommonJS 在JS早期,使用script标签引入JS,会造成以下问题:加载的时候阻塞......
  • 携程Java三面面经,已拿 offer!!
    分享一位读者投稿的携程校招Java岗位的面经。下面是正文。个人背景:双非本,机械专业转码。携程在正式面试之前,会有一个性格测试(40分钟)。性格测试之后,大概过一周进行笔试......
  • Java项目集成工作流activiti,会签
    前言activiti工作流引擎项目,企业erp、oa、hr、crm等企事业办公系统轻松落地,一套完整并且实际运用在多套项目中的案例,满足日常业务流程审批需求。一、项目形式springboot......
  • MyBatis_10(分页插件)
    主题:分页插件一、分页插件使用步骤:1-添加依赖<!--https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper--><dependency> <groupId>com.github......
  • JAVA-构造方法
           ......
  • How to make an HTTP request in Javascript?
    YoucanmakeanHTTPrequestinJavaScriptusingthebuilt-infetch()functionortheXMLHttpRequest(XHR)object.Hereareexamplesofhowtouseeachofthes......
  • java-数组,冒泡排序19
    packagecom.demo.data;publicclassarr{publicstaticvoidmain(String[]args){int[]arr={11,22,33,44,999};intmax=m(arr);......