Mybatis笔记2

使用Mybatis完成的CRUD操作

个人总结的一些小规律

img

学习过程中碰到的错误:

org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

虽然报错信息提示的 很明显是sql语法报错,不过我一时之间没有没有看出sql语句错在哪里,后来才发现是插入sql语句的括号写错了,不是小括号,而是大括号

错误写法:insert  into user(username,address,sex,birthday)value(#(username),#(address),#(sex),#(birthday);

正确写法:insert  into user(username,address,sex,birthday)value(#{username},#{address},#{sex},#{birthday});

JavaBean类

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

dao层

package com.itheima.dao;

import com.itheima.domain.User;

import java.util.List;

public interface IUserDao {
    //查询所有用户
    List<User> findAll();
    //保存用户
    void saveUser(User user);
    //更新用户
    void updateUser(User user);
    //根据id删除用户
    void deleteUser(Integer userId);
    //查询一个,根据id查询用户信息
    User findById(Integer userId);
    //根据名称模糊查询用户信息
    List<User> findByName(String username);
    //查询总用户数
    int findTotal();
}

配置文件

<?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.itheima.dao.IUserDao">
    <!--查询所有用户-->
    <select id="findAll" resultType="com.itheima.domain.User">
      select * from user;
    </select>
<!--保存用户-->
    <insert id="saveUser" parameterType="com.itheima.domain.User">
       <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
           select last_insert_id();
       </selectKey>
        insert  into user(username,address,sex,birthday)value(#{username},#{address},#{sex},#{birthday});
    </insert>
    <!--更新用户-->
    <update id="updateUser" parameterType="com.itheima.domain.User">
        update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
    </update>
    <!--删除用户-->
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{id}
    </delete>
    <!--根据id查询用户-->
    <select id="findById"  parameterType="Integer" resultType="com.itheima.domain.User">
        select * from user where id = #{uid}
    </select>

    <!--根据名称模糊查询-->
    <select id="findByName" parameterType="String" resultType="com.itheima.domain.User">
        select * from user where username like #{name}
    </select>
    <select id="findTotal" resultType="int">
        select count(id) from user;
    </select>
</mapper>

测试类

package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisTest {
    private InputStream in;//读取配置文件
    private SqlSession sqlSession;//操作数据库
    private IUserDao userDao;
    @Before//用于在测试方法执行之前执行,在其他方法执行之前执行init方法
    public void init() throws IOException {
        //读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //获取sqlSession对象
       sqlSession = factory.openSession();
        //获取dao的代理对象
        userDao = sqlSession.getMapper(IUserDao.class);
    }
    @After//用于测试方法执行之后执行
    public void destroy() throws IOException {
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
        in.close();
    }
    @Test
    //查询所有用户
    public void testFindAll() throws IOException {
        //执行查询方法
        List<User> users = userDao.findAll();
        for(User user:users){
            System.out.println(user);
        }
    }
    @Test
    //保存用户
    public void testSave(){
        User user = new User();
        user.setUsername("王五");
        user.setAddress("北京市");
        user.setSex("男");
        user.setBirthday(new Date());
        System.out.println("保存前"+user);
        //执行保存方法
        userDao.saveUser(user);
        System.out.println("保存后"+user);
    }

    @Test
    //更新用户
    public void testUpdate(){
        User user = new User();
        user.setId(50);
        user.setUsername("李四");
        user.setAddress("北京市");
        user.setSex("男");
        user.setBirthday(new Date());
        //执行查询方法
        userDao.updateUser(user);
    }
    @Test
    //删除用户
    public void testDelete(){

        userDao.deleteUser(48);
    }
    @Test
    //查询一个用户
    public void testFindOne(){

        User user = userDao.findById(48);
        System.out.println(user);
    }

    @Test
    //查询一个用户
    public void testFindByName(){

        List<User> users = userDao.findByName("%王%");
        for(User user :users){
            System.out.println(user);
        }
    }
    @Test
    //查询一个用户
    public void testFindTotal(){
        int count = userDao.findTotal();
        System.out.println(count);
    }
}

typeAliases标签和Package标签

<!--使用typeAliases配置别名,他只能配置domain中类的别名-->
    <typeAliases>
        <!--typeAlias用于配置别名,type属性指定的是实体类权限定类名 alias属性指定别名,当指定了别命,不再区分大小写-->
        <!--<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>-->
        <!--用于指定配置别名的包,当指定之后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写-->
        <package name="com.itheima.domain"></package>
    </typeAliases>
<mappers>
    <!--<mapper resource="com/itheima/dao/IUserDao.xml"></mapper>-->
    <!--package标签是用于指定dao接口所在的包,当指定了之后就不需要在写mapper以及resource或者class了-->
    <package name="com.itheima.dao"></package>
</mappers>

mybatis连接池的分类

连接池:我们在实际开发中都会使用连接池,因为他可以减少我们获取连接所消耗的时间

mybatis中的连接池

mybatis连接池提供了3种方式的配置:

配置的位置:主配置文件SqlMapConfig.xml的dataSource标签,type属性就是表示采用何种连接池方式

type属性的取值有三种

1.POOLED 采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现

2.UNPOOLED 采用的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用池的思想

3.采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样的,如果不是web或者maven的war工程,是不能使用的(tomcat服务器,采用连接池就是dbcp连接池)

posted @ 2019-07-14 22:45  train99999  阅读(256)  评论(0编辑  收藏  举报