Mybatis入门之增删改查

Mybatis入门之增删改查

Mybatis如果操作成功,但是数据库没有更新那就是得添加事务了。(增删改都要添加)-----

浪费了我40多分钟怀疑人生后来去百度。。。

导入包:

 

 

引入配置文件:

sqlMapConfig.xml(mybatis的核心配置文件)、log4j.properties(日志记录文件)

<?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>
    <!-- 和Spring整合后 environments配置将废除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    
    <!-- 加载映射文件 -->
    <mappers>
        <mapper resource="deep/sqlmap/Account.xml"/>
    </mappers>
</configuration>
#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

 

数据库准备:(略)

实体类编写后针对实体类编写的映射文件

<?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:命名空间,用于隔离sql -->
<mapper namespace="account">
    <!-- 通过ID查询一个用户 -->
    <!-- parameterType入参的类型,resultType返回值的类型 -->
    <!-- #{v} 参数占位符 -->
    <select id="findUserById" parameterType="Integer" resultType="deep.pojo.Account">
        select * from account where id = #{v}
    </select>
    
    <!-- 
        #{}            占位符  
        ${}            字符串拼接
     -->
    <!-- 根据用户名模糊查询用户列表 -->
    <select id="findUserByUsername" parameterType="String" resultType="deep.pojo.Account">
        <!-- 这种方式不防止sql注入 -->
        <!-- select * from account where username like '%${value}%' -->
        select * from account where username like "%"#{v}"%"
    </select>
    
    <!-- 添加用户 -->
    <insert id="insertUser" parameterType="deep.pojo.Account">
        <!-- 在查询结束后查询最新插入的id,并返回给对象,赋值给对象的id属性 -->
        <selectKey keyProperty="id" resultType="Integer" order="AFTER">
            select LAST_INSERT_ID() 
        </selectKey>
        insert into account (username,birthday,address,sex)
        value (#{username},#{birthday},#{address},#{sex})
    </insert>
    
    <!-- 更新 -->
    <update id="updateUserById" parameterType="deep.pojo.Account">
        update account
        set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}
        where id = #{id}
    </update>
    
    <!-- 删除 -->
    <delete id="deleteUserById" parameterType="Integer">
        delete from account
        where id = #{v}
    </delete>
    
</mapper>    

 

执行

package deep.junit;


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

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.Test;

import deep.pojo.Account;

public class MyBatisFirstTest {
    
    @Test
    public void testMybatis() throws Exception {
        //加载核心配置文件
        String resource = "sqlMapConfig.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        //执行sql语句
        Account account = sqlSession.selectOne("account.findUserById", 1);
        
        System.out.println(account);
    }
    
    //根据用户名称模糊查询用户列表
    @Test
    public void testFindUserByUsername() throws Exception{
        String resource = "sqlMapConfig.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        //执行sql语句
        List<Account> accounts = sqlSession.selectList("account.findUserByUsername", "五");
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
    
    //根据用户名称模糊查询用户列表
        @Test
        public void testInsertUser() throws Exception{
            String resource = "sqlMapConfig.xml";
            InputStream in = Resources.getResourceAsStream(resource);
            
            //创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            
            //创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            
            //执行sql语句
            Account account = new Account();
            account.setUsername("麻子2");
            account.setBirthday(new Date());
            account.setAddress("sdfasdfads");
            account.setSex("男");
            int i = sqlSession.insert("account.insertUser", account);
            
            //自己手动提交事务
            sqlSession.commit();
            
            System.out.println(account.getId());
        }
    
    
    //更新用户
        @Test
        public void testUpdateUserById() throws Exception{
            String resource = "sqlMapConfig.xml";
            InputStream in = Resources.getResourceAsStream(resource);
            
            //创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            
            //创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            
            //执行sql语句
            Account account = new Account();
            account.setId(28);
            account.setUsername("麻子更新");
            account.setBirthday(new Date());
            account.setAddress("地址更新");
            account.setSex("女");
            int update = sqlSession.update("account.updateUserById", account);
            
            //自己手动提交事务
            sqlSession.commit();
        }
    
        //更新用户
                @Test
                public void testDelete() throws Exception{
                    String resource = "sqlMapConfig.xml";
                    InputStream in = Resources.getResourceAsStream(resource);
                    
                    //创建SqlSessionFactory
                    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
                    
                    //创建SqlSession
                    SqlSession sqlSession = sqlSessionFactory.openSession();
                    
                    sqlSession.delete("account.deleteUserById", 28);
                    
                    //自己手动提交事务
                    sqlSession.commit();
                }
    
}

 

posted @ 2019-02-27 15:35  程序员deepz  阅读(191)  评论(0编辑  收藏  举报