mybatis——入门demo

文章目录

  • 1 demo
    • 1.1 导入相关依赖
    • 1.2 SqlMapConfig.xml
    • 1.3 User和UserMapper.xml
    • 1.4 测试
  • 2 #{}和${}区别
  • 3 OGNL
  • 4 主键返回
  • 5 CRUD
    • 5.1 添加
    • 5.2 删除
    • 5.3 更新

1 demo

mybatis——入门demo_第1张图片

1.1 导入相关依赖

 <dependencies>
 		
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.6version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
    dependencies>

1.2 SqlMapConfig.xml

mybatis的全局配置文件,配置了mybatis的运行环境等信息。



<configuration>
    <properties resource="db.properties">properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            dataSource>
        environment>
    environments>
    <mappers>
        <mapper resource="UserMapper.xml" />
    mappers>
configuration>

db.properties

db.driver=com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/shop
db.username = root
db.password=root

1.3 User和UserMapper.xml

User.java实体类

public class User {
    int id;
    String username;
    String password;
    String email;
    String phone;
    String address;
    //省略toString,get,set

新建user表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8

UserMapper.xml



<mapper namespace="test">
    <select id="findUserById" parameterType="int"
            resultType="User">
        SELECT * from user WHERE id=#{id}
    select>
mapper>

1.4 测试

public class MyBatisTest {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void creatSqlSessionFactory() throws IOException {
        String resource = "SqlMapConfig.xml";
        // 读取SqlMapConfig文件
        InputStream in = Resources.getResourceAsStream(resource);
        //创建sqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    }

    @Test
    public void testFindUserById(){
        SqlSession sqlSession =null;
        try {
        	//  获取SqlSeesion
            sqlSession = sqlSessionFactory.openSession();
            // 查询
            User user = sqlSession.selectOne("test.findUserById",1);
            // 输出
            System.out.println(user);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession!=null)
                sqlSession.close();
        }
    }
}

输出结果

User{id=1, username='aaa', password='aaa', email='[email protected]', phone='aaa', address='aaa'}

2 #{}和${}区别

#{}:

  • 相当于JDBC SQL语句中占位符?(preparedStatement)
  • 进行输入映射时,会对参数进行类型解析(如果是String类型,那么SQL语句会自动加上‘’)
  • 如果进行简单类型(String,Date、8种基本类型的包装类)的输入映射时,#{}中的参数名称可以任意

${}

  • 相当于JDBC SQL语句中的连接符号+statement
  • 存在sql注入的问题,使用or 1=1关键字将查询条件忽略
  • 进行输入映射时,不会进行类型解析
  • 如果进行简单类型的输入映射时,${}的参数名称必须是value

3 OGNL

对象导航图语言

|--user(参数值对象)
    |--username--测试
    |--password--123
    |--depa--Department
        |--name--测试
        |--number--121

4 主键返回

  <selectKey keyProperty="id" order="AFTER" resultType="int">
            select Last_INSERT_ID()
  selectKey>

keyProperty:指定返回的主键存储在pojo中的那个属性
order:selectKey标签中的sql执行顺序,是相对与insert语句来说的,由于mysql的自增原理。执行完insert语句之后才将主键生成,所以这里selectKey的执行顺序为after

5 CRUD

5.1 添加

UserMapper.xml

 <insert id="addUser" parameterType="User">
        
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        selectKey>
        INSERT INTO user(username,password,email,phone,address)
        VALUES (#{username},#{password},#{email},#{phone},#{address})
    insert>

test

@Test
    public void testAddUser(){
        SqlSession sqlSession =null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            User user = new User("小小", "111", "1@com", "123", "sasas");
            int count =sqlSession.insert("test.addUser", user);
            System.out.println(count);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession!=null)
                sqlSession.close();
        }

    }

5.2 删除

UserMapper.xml

<delete id="deleteUserById" parameterType="int">
        DELETE FROM user WHERE id =#{id}
    delete>
 @Test
    public void testDeleteUser(){
        SqlSession sqlSession =null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            int count =sqlSession.delete("test.deleteUserById", 13);
            System.out.println(count);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession!=null)
                sqlSession.close();
        }
    }

5.3 更新

UserMapper.xml

<update id="updateUser" parameterType="User">
        UPDATE user set username=#{username},email=#{email},phone=#{phone},address =#{address}
        WHERE id =#{id}
    update>
@Test
    public void testUpdateUser(){
        SqlSession sqlSession =null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            User u =new User("修改","1234","test@","121212","");
            u.setId(1);
            int count =sqlSession.update("test.updateUser", u);
            System.out.println(count);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession!=null)
                sqlSession.close();
        }
    }

你可能感兴趣的:(mybatis)