Mybatis 创建项目和 增删改查

创建项目

1 先创建maven项目
Mybatis 创建项目和 增删改查_第1张图片
Mybatis 创建项目和 增删改查_第2张图片

然后配置pom.xml文件mybatis、mysql-connector-java、log4j、junit

<dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        //mysql看自己的版本
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
<build>
        <resources>
            <!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml
                    
                
            
            
            
                src/main/resources
            
        
    

配置日志log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

pojo



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

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

    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 Date getBirthday() {
        return birthday;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

mybatis-config.xml

<configuration>
            <!--使用dev环境-->
            <environments default="dev">
                <!--dev环境-->
                <environment id="dev">
                    <transactionManager type="JDBC"></transactionManager>
                    <!--使用连接池中的数据源-->
                    <dataSource type="POOLED">
                        <property name="driver" value="com.mysql.jdbc.Driver"/>
                        <!--自己的-->
                        <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8"/>
                        <property name="username" value="root"/>
                        <property name="password" value="1111"/>
                    </dataSource>
                </environment>
            </environments>
            <!-- 扫描映射文件 -->
            <mappers>
                <mapper resource="com/by/dao/UserDao.xml"/>
            </mappers>
        </configuration>

userDao

package com.jyx.dao;

import com.jyx.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface UserDao {
    List<User> findAll();
    User findUserById(Integer id);
    User findUserByIdAndName(Integer id, String username);
    User findUserByIdAndName2(@Param("id")Integer id ,@Param("username") String username );
    User findUserByuserInfo(User user);
    User findUserByMap(Map<String,Object> map);

    List<User> findUserByName(String username);

    void deleteUserById(Integer id);

    void updateUserById(User user);

    void insertUser(User user);
}

UserDao.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">
<!--namespace:唯一,接口全类名-->
<mapper namespace="com.jyx.dao.UserDao">
    <!--
        id:和接口方法名保持一致
        resultType:和接口返回类型保持一致
    -->
    <select id="findAll" resultType="com.jyx.pojo.User">
        select * from user
    </select>
    <select id="findUserById" parameterType="java.lang.Integer" resultType="com.jyx.pojo.User">
        select  * from user where id =#{id}
    </select>
    <select id="findUserByIdAndName" resultType="com.jyx.pojo.User">
        select * from user  where id=#{param1} and username=#{param2}
    </select>
    <select id="findUserByIdAndName2" resultType="com.jyx.pojo.User">
        select * from user  where id=#{id} and username=#{username}
    </select>
    <select id="findUserByuserInfo" resultType="com.jyx.pojo.User">
        select * from user  where id=#{id} and username=#{username}
    </select>
    <select id="findUserByMap" resultType="com.jyx.pojo.User">
        select * from user  where id=#{id} and username=#{username}
    </select>
    <select id="findUserByName" parameterType="java.lang.String" resultType="com.jyx.pojo.User">
        select * from user  where username like '%${value}%'
    </select>
    <delete id="deleteUserById" parameterType="java.lang.Integer">
        DELETE FROM user
        WHERE id =#{id}
    </delete>
    <update id="updateUserById" parameterType="com.jyx.pojo.User">
        update user set username=#{username},
                        birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>
<!--    <insert id="insertUser" parameterType="com.jyx.pojo.User">-->
<!--        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">-->
<!--            select last_insert_id();-->
<!--        </selectKey>-->
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.jyx.pojo.User">
        insert into user(username,birthday,sex,address)
        values(#{username},#{birthday},#{sex},#{address});
    </insert>


</mapper>

User

package com.by.pojo;

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

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

    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 Date getBirthday() {
        return birthday;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

测试类
MvBatisTest

package com.jyx.test;

import com.jyx.dao.UserDao;
import com.jyx.pojo.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.HashMap;
import java.util.List;
import java.util.Map;

public class MvBatisTest {
    private SqlSession sqlSession;
    private InputStream inputStream;
    @Before
    public void init() throws IOException {
        //加载配置文件
        String resource = "mybatis-config.xml";
         inputStream = Resources.getResourceAsStream(resource);

        //创建sqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获得数据的会话实例
         sqlSession= sessionFactory.openSession();
    }
    @Test
    public void testFindUserById ()  {

        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.findUserById(41);
        System.out.println(user);
    }
    @Test
    public void findUserByIdAndName ()  {

        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.findUserByIdAndName(41,"张三丰");
        System.out.println(user);
    }
    @Test
    public void findUserByIdAndName2 ()  {

        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.findUserByIdAndName2(41,"张三丰");
        System.out.println(user);
    }
    @Test
    public void findUserByIdAndName3 ()  {


        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User userInfor=new User();
        userInfor.setId(41);
        userInfor.setUsername("张三丰");
        User user=userDao.findUserByuserInfo(userInfor);
        System.out.println(user);
    }
    @Test
    public void findUserByIdAndName4 ()  {



        UserDao userDao = sqlSession.getMapper(UserDao.class);
        Map<String,Object> map =new HashMap<>();
        map.put("id",41);
        map.put("username","张三丰");

        User user=userDao.findUserByMap(map);
        System.out.println(user);
    }
    @Test
    public void findUserByName ()  {



        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> users=userDao.findUserByName("张");
        for (User user:users){
            System.out.println(user);
        }
    }
    @Test
    public void testDeleteUserById ()  {
        UserDao userDao = sqlSession.getMapper(UserDao.class);
       userDao.deleteUserById(42);
    }
    @Test
    public void testupdateUserById(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = new User();
        user.setUsername("aa");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("高老庄");
        user.setId(42);
        userDao.updateUserById(user);
    }
    @Test
    public void testInsterUser(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = new User();
        user.setUsername("刘德华");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("香港");
        userDao.insertUser(user);
        System.out.println("新增记录的id值:"+user.getId());
    }




@After
    public void cl() throws IOException {
        sqlSession.close();
        inputStream.close();
}


}


单个参数绑定

Dao

public User findUserById(Integer id);

UserDao.xml

   parameterType:指定输入参数的类型
   resultType:指定数据结果封装的数据类型
   #{id}:它代表占位符,相当于原来 jdbc 部分所学的?,都是用于替换实际的数据。
    <select id="findUserById" parameterType="java.lang.Integer" 
            				  resultType="com.by.pojo.User" >
        select * from user where id=#{id}<!--只有一个参数时,#{任意书写}-->
    </select>

测试类

    @Test
    public void testFindUserById(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.findUserById(41);
        System.out.println(user);
    }

序号参数绑定

    //传递多个参数
    public User findUserByIdAndName(Integer id, String username);

UserDao.xml

     <select id="findUserByIdAndName" resultType="com.by.pojo.User" >
        SELECT * FROM user
        WHERE id = #{arg0} AND username = #{arg1} <!--arg0 arg1 arg2 ...-->
    </select>
    

或者

	<select id="findUserByIdAndName" resultType="com.by.pojo.User" >
        SELECT * FROM user
        WHERE id = #{param1} AND username = #{param2} <!--param1 param2 param3 ...-->
    </select>

测试类

    @Test
    public void testFindUserByIdAndName(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.findUserByIdAndName(41,"张三丰");
        System.out.println(user);
    }

注解参数绑定

    //传递多个参数
    public User findUserByIdAndName2(@Param("id")Integer id,
                                     @Param("username")String username);

UserDao.xml

    <select id="findUserByIdAndName2" resultType="com.by.pojo.User" >
        SELECT * FROM user
        WHERE id = #{id} AND username = #{username}
    </select>
    

测试类

    @Test
    public void testFindUserByIdAndName2(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.findUserByIdAndName2(41,"张三丰");
        System.out.println(user);
    }

对象参数绑定

    //使用对象属性进行参数绑定
    public User findUserByUserInfo(User user);

UserDao.xml

    <select id="findUserByUserInfo" parameterType="com.by.pojo.User" 
            									resultType="com.by.pojo.User">
        SELECT * FROM user
        WHERE id = #{id} AND username = #{username}<!--参数为对象时,#{属性名}-->
    </select>

测试类

    @Test
    public void testFindUserByName(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User userInfo = new User();
        userInfo.setId(41);
        userInfo.setUsername("张三丰");
        User user = userDao.findUserByUserInfo(userInfo);
        System.out.println(user);
    }

Map参数绑定

	//使用Map进行参数绑定
	public User findUserByMap(Map<String, Object> map);

UserDao.xml

    <select id="findUserByMap" 
            parameterMap="java.util.Map" resultType="com.by.pojo.User">
        SELECT * FROM user
        WHERE id = #{id} AND username = #{username}
    </select>

测试类

    @Test
    public void testFindUserByMap(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id",41);
        map.put("username","张三丰");
        User user = userDao.findUserByMap(map);
        System.out.println(user);
    }

模糊查询

    //模糊查询
    public  List<User> findUserByName(String username);

UserDao.xml

    <select id="findUserByName" parameterType="string" resultType="com.by.pojo.User">
        <!-- select * from user where username like concat('%',#{username},'%') -->
        select * from user where username like '%${value}%'<!--${}括号中只能是value-->
    </select>

测试类

    @Test
    public void testFindUserByName(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.findUserByName("张");
        for (User user : userList) {
            System.out.println(user);
        }
    }

sql注入

    //sql注入
    public User login(User user);

UserDao.xml

    <select id="login" parameterType="com.by.pojo.User" resultType="com.by.pojo.User">
        select * from user where username = '${username}' and password = '${password}'
    </select>

测试类

    @Test
    public void testLogin(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User userInfo = new User();
        userInfo.setUsername("张三丰' #");
        userInfo.setPassword("123");
        User user = userDao.login(userInfo);
        System.out.println(user);
    }
Sql注入 底层 jdbc类型转换 单个简单类型的参数
$ 不防止 Statement 不转换 value
# 防止 preparedStatement 转换 任意

​ 结论:除模糊匹配外,杜绝使用${}

  • #{}符
    1. #{}表示一个占位符号 通过#{}可以实现 preparedStatement 向占位符中设置值,自动进行 java 类型和 jdbc 类型转换
    2. #{}可以接收简单类型值或 pojo 属性值。 如果 parameterType 传输单个简单类 型值,#{}括号中可以是 value 或其它名称。
    3. #{}可以有效防止 sql 注入。
  • ${}符
    1. 表示拼接 s q l 串通过 {}表示拼接 sql 串 通过 表示拼接sql串通过{}可以将 parameterType 传入的内容拼接在 sql 中且不进行 jdbc 类型转换
    2. 可以接收简单类型值或 p o j o 属性值,如果 p a r a m e t e r T y p e 传输单个简单类型值, {}可以接收简单类型值或 pojo 属性值,如果 parameterType 传输单个简单类型值, 可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,{}括号中只能是 value

删除

    //删除
    public void deleteUserById(Integer id);

UserDao.xml

    <delete id="deleteUserById" parameterType="Integer">
        DELETE FROM user
        WHERE id = #{id}
    </delete>

测试类

    @Test
    public void testDeleteUserById(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        userDao.deleteUserById(41);
        sqlSession.commit();
    }

添加

    //添加
    public void insertUser(User user);

UserDao.xml

<insert id="insertUser" parameterType="com.by.pojo.User">
        <!--
            主键回填:新增之后,获取新增记录的id值
            keyProperty="id":主键对应实体类的属性
            order="AFTER":先执行插入语句,之后再执行查询语句
            resultType="java.lang.Integer":主键的数据类型
        -->
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            /*查询出刚刚插入的记录自增长id*/
            select last_insert_id();
        </selectKey>
        insert into user(username,password,birthday,sex,address)
        values(#{username},#{password},#{birthday},#{sex},#{address});
</insert>

或者

	<!--
        useGeneratedKeys=true”:获取数据库生成的主键
        keyProperty=“id”:主键对应实体类的属性
    -->
    <insert id="insertUser" useGeneratedKeys="true" 
            keyProperty="id" parameterType="com.by.pojo.User">
        <!--
            主键回填:新增之后,获取新增记录的id值
            keyProperty="id":主键对应实体类的属性
            order="AFTER":先执行插入语句,之后再执行查询语句
            resultType="java.lang.Integer":主键的数据类型

            <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
                /*查询出刚刚插入的记录自增长id*/
                select last_insert_id();
            </selectKey>
         -->
        insert into user(username,password,birthday,sex,address)
        values(#{username},#{password},#{birthday},#{sex},#{address});
    </insert>

测试类

    @Test
    public void testInsertUser(){
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = new User();
        user.setUsername("刘德华");
        user.setPassword("111");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("香港");
        userDao.insertUser(user);
        System.out.println("新增记录的id值:"+user.getId());
        sqlSession.commit();
    }

你可能感兴趣的:(Mybatis,mybatis)