MyBatis学习笔记(一)

dao层

public interface UserDao {
    User selectById(Long id);
    int insertUser(User user);
    List<User> selectUser();

dao.impl

public class UserDaoImpl implements UserDao {
    @Override
    public User selectById(Long id) {
        SqlSession sqlSession = MybatisUtil.openSession();
        String sqlId = "org.niit.dao.UserDao.selectById";
        User user = sqlSession.selectOne(sqlId,id);
        return user;
    }

    @Override
    public int insertUser(User user) {
        SqlSession sqlSession = MybatisUtil.openSession();
        String sqlId = "org.niit.dao.UserDao.insertUser";
        int rows = sqlSession.insert(sqlId,user);
        sqlSession.commit();
        return rows;
    }

    @Override
    public List<User> selectUser() {
        SqlSession sqlSession = MybatisUtil.openSession();
        String sqlId = "org.niit.dao.UserDao.selectUser";
        List<User> list = sqlSession.selectList(sqlId);
        return list;
    }

user类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private String phone;
    private String email;
    private Date gmtCreate;
    private Date loginTime;

    public User(String username, String password, Integer age, String phone, String email, Date gmtCreate, Date loginTime) {
        this.username = username;
        this.password = password;
        this.age = age;
        this.phone = phone;
        this.email = email;
        this.gmtCreate = gmtCreate;
        this.loginTime = loginTime;
    }
MybatisUtil类
 private static  SqlSessionFactory sqlSessionFactory = null;
    //静态代码块
    static {
        try {
            /** 1、定义 mybatis 主配置文件的位置, 从类路径开始的相对路径 */
            String mybatisConfig = "mybatis-config.xml";
            /** 2、读取主配置文件,使用 mybatis 框架中的 Resources 类 */
            InputStream inputStream = Resources.getResourceAsStream(mybatisConfig);
            /** 3、创建 SqlSessionFactory 对象,使用 SqlSessionFactoryBuilder 类 */
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //获取SqlSession
    public static SqlSession openSession(){
        SqlSession sqlSession = null;
        if(sqlSessionFactory != null){
            sqlSession = sqlSessionFactory.openSession();
        }
        return sqlSession;
    }

UserMapper.xml

<?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">
<!--
1、约束文件:http://mybatis.org/dtd/mybatis-3-mapper.dtd
    【作用】定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序(Idea基于该文件对我们的代码进行提示及校验)
2、mapper是根标签
    namespace:命名空间,必须有值,不能为空。唯一值。推荐使用DAO接口的全限定名称。
    【作用】参与识别 SQL 语句的作用。
3、在 mapper 里可以写<select>、<insert>、<update>、<delete> 等标签。
-->
<mapper namespace="org.niit.dao.UserDao">

    <!--查询用户信息-->
    <select id="selectById" resultType="user" parameterType="java.lang.Long">
        select * from tb_user where id = #{id};
    </select>
    <!--插入用户信息-->
    <insert id="insertUser">
        INSERT INTO tb_user (username, password, age, phone, email, gmt_create, login_time)
        VALUES (#{username},
                #{password},
                #{age},
                #{phone},
                #{email},
                #{gmtCreate},
                #{loginTime}
                )
    </insert>
    <select id="selectUser" resultType="user" >
        select * from tb_user
    </select>

</mapper>
<?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>
    
    <settings>
        <!-- 配置是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。默认为:false -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--在 configuration 标签下配置日志 此处使用:STDOUT_LOGGING 日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--通过 typeAlias 元素进行配置,其 type 属性配置 Java Bean 的完全限定名,alias 为别名进行命名。-->
    <typeAliases>
       <!-- <typeAlias type="com.niit.domain.User" alias="user"></typeAlias>-->
        <package name="org.niit.domain"/>
    </typeAliases>
    <!--配置数据源等环境信息-->
    <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/2020_pp1"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!-- 加载映射文件 -->
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

mybatis-config.xml

测试类

TestUserDaoImpl
public class TestUserDaoImpl {
    @Test
    public void testOne(){
        UserDao dao = new UserDaoImpl();
        User user = dao.selectById(33l);
        System.out.println("====================返回用户信息"+user);
    }
    @Test
    public void testTwo(){
        UserDao dao = new UserDaoImpl();
        int row = dao.insertUser( new User("王三","123456",22,"15709581306","123@qq.com",new Date(),new Date()));
        System.out.println("插入"+row+"条信息");
    }
    @Test
    public void testThree(){
        UserDao dao = new UserDaoImpl();
        for (User user : dao.selectUser()) {
            System.out.println(user);
        }

    }

TestUserDaoByPxo
public class TestUserDaoByPxo {
    SqlSession sqlSession = null;
    UserDao userDao = null;
    @BeforeClass
    public static  void beforeClass(){
        System.out.println("==============BeforeClass===================");
    }

    @Before
    public void setUp(){
        System.out.println("==============测试方法之前执行====================");
        sqlSession = MybatisUtil.openSession();
        //获取Dao动态代理对象
        userDao  = sqlSession.getMapper(UserDao.class);
    }
    @After
    public void after(){
        System.out.println("==============测试方法之后执行====================");
        sqlSession.close();
    }
    @Test
    public void testOne(){
        User user = userDao.selectById(33l);
        System.out.println("====================返回用户信息================"+user);

    }
    @Test
    public void testTwo(){
        User user = new User();
        user.setUsername("tyut5");
        user.setPhone("15788866666");
        user.setPassword("123");
        user.setAge(14);
        user.setGmtCreate(new Date());
        int rows = userDao.insertUser(user);
        System.out.println("插入"+rows+"条信息~~~~~~~~~~~~~");
        sqlSession.commit();
    }
TestUserDaoImpl
public class TestUserDaoImpl {
    @Test
    public void testOne(){
        UserDao dao = new UserDaoImpl();
        User user = dao.selectById(33l);
        System.out.println("====================返回用户信息"+user);
    }
    @Test
    public void testTwo(){
        UserDao dao = new UserDaoImpl();
        int row = dao.insertUser( new User("王三","123456",22,"15709581306","123@qq.com",new Date(),new Date()));
        System.out.println("插入"+row+"条信息");
    }
    @Test
    public void testThree(){
        UserDao dao = new UserDaoImpl();
        for (User user : dao.selectUser()) {
            System.out.println(user);
        }

    }

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.niit</groupId>
    <artifactId>mybatis_demo_pp</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis_demo1</module>
    </modules>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!--mybatis 依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--MySql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <!--Junit单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

数据库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哩吇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值