mybatis学习之普通增删改查

Posted 2312947032zyk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis学习之普通增删改查相关的知识,希望对你有一定的参考价值。

mybatis下载地址:https://github.com/mybatis/mybatis-3/releases

选择你要下载的版本,这里我下载的3.4.2版

项目结构:

技术图片

将mybatis中的所有jar包导入还要导入链接mysql数据库的jar包。

其中db.properties,mybatis-config.xml,log4j.properties是在src下。

在mysql中新建mybatis数据库,在数据库中新建表t_customer,表结构如下:

技术图片

随后向其中随便插入几条数据。

Customer.java

 1 package com.itheima.po;
 2 
 3 public class Customer 
 4     private Integer id;
 5     private String username;
 6     private String jobs;
 7     private String phone;
 8     @Override
 9     public String toString() 
10         return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";
11     
12     
13     public Integer getId() 
14         return id;
15     
16     public void setId(Integer id) 
17         this.id = id;
18     
19     public String getUsername() 
20         return username;
21     
22     public void setUsername(String username) 
23         this.username = username;
24     
25     public String getJobs() 
26         return jobs;
27     
28     public void setJobs(String jobs) 
29         this.jobs = jobs;
30     
31     public String getPhone() 
32         return phone;
33     
34     public void setPhone(String phone) 
35         this.phone = phone;
36     
37     
38 

 MybatisUtils.java

 1 package com.itheima.utils;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.io.Reader;
 6 
 7 import org.apache.ibatis.io.Resources;
 8 import org.apache.ibatis.session.SqlSession;
 9 import org.apache.ibatis.session.SqlSessionFactory;
10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
11 
12 public class MybatisUtils 
13     private static SqlSessionFactory sqlSessionFactory=null;
14     
15     //初始化sqlSessionFactory
16     static 
17         try 
18             Reader reader=Resources.getResourceAsReader("mybatis-config.xml");
19             sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
20          catch (IOException e) 
21             // TODO Auto-generated catch block
22             e.printStackTrace();
23         
24     
25     
26     
27     public static SqlSession getSqlSession() 
28         return sqlSessionFactory.openSession();
29         
30     
31 

MybatisTest.java

  1 package com.itheima.test;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.util.List;
  6 
  7 import org.apache.ibatis.io.Resources;
  8 import org.apache.ibatis.session.SqlSession;
  9 import org.apache.ibatis.session.SqlSessionFactory;
 10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 11 import org.junit.Test;
 12 
 13 import com.itheima.po.Customer;
 14 import com.itheima.po.User;
 15 import com.itheima.utils.MybatisUtils;
 16 
 17 //mybatis入门程序测试
 18 
 19 public class MybatisTest 
 20     
 21     
 22     @Test
 23     public void findCustomerById() throws IOException 
 24 //        //1.读取配置文件
 25 //        String resourceString="mybatis-config.xml";
 26 //        InputStream inputStream=Resources.getResourceAsStream(resourceString);
 27 //        //根据配置文件构建SqlSessionFactory
 28 //        SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
 29 //        //通过SqlSessionFactory创建sqlsession
 30 //        SqlSession sqlSession=sessionFactory.openSession();
 31 //        //sqlSession执行映射文件中的sql语句,并返回结果
 32 //        //第一个参数为mapper.xml中的id,第二个是传入的占位符就是#id的值
 33          SqlSession sqlSession=MybatisUtils.getSqlSession();
 34         
 35         
 36         Customer customer=sqlSession.selectOne("com.itheima.po.Customer.findCustomerById", 1);
 37         System.out.println(customer.toString());
 38         //关闭sqlsession
 39         sqlSession.close();
 40     
 41     @Test
 42     public void findCustomerByName() throws IOException 
 43         //1.读取配置文件
 44         String resource="mybatis-config.xml";
 45         InputStream inputStream=Resources.getResourceAsStream(resource);
 46         //根据配置文件构建SqlSessionFactory
 47         SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
 48         //通过SqlSessionFactory创建sqlsession
 49         SqlSession sqlSession=sessionFactory.openSession();
 50         List<Customer> customers= sqlSession.selectList("com.itheima.po.Customer.findCustomerByName","j");
 51         for (Customer customer:customers) 
 52             System.out.println(customer.toString());
 53         
 54         sqlSession.close();
 55     
 56     @Test
 57     public void addCustomerTest() throws IOException 
 58         //1.读取配置文件
 59                 String resource="mybatis-config.xml";
 60                 InputStream inputStream=Resources.getResourceAsStream(resource);
 61                 //根据配置文件构建SqlSessionFactory
 62                 SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
 63                 //通过SqlSessionFactory创建sqlsession
 64                 SqlSession sqlSession=sessionFactory.openSession();
 65                 Customer customer=new Customer();
 66                 customer.setUsername("zyk");
 67                 customer.setJobs("hero");
 68                 customer.setPhone("15035766618");
 69                 int row=sqlSession.insert("com.itheima.po.Customer.addCustomer", customer);
 70                 if(row>0) 
 71                     System.out.println("插入了"+row+"数据");
 72                 else 
 73                     System.out.println("插入失败");
 74                 
 75                 //注意要提交事务,增删改都涉及到事务
 76                 sqlSession.commit();
 77                 sqlSession.close();
 78     
 79     @Test
 80     public void updateCustomerTest() throws IOException 
 81         //1.读取配置文件
 82                 String resource="mybatis-config.xml";
 83                 InputStream inputStream=Resources.getResourceAsStream(resource);
 84                 //根据配置文件构建SqlSessionFactory
 85                 SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
 86                 //通过SqlSessionFactory创建sqlsession
 87                 SqlSession sqlSession=sessionFactory.openSession();
 88                 Customer customer=new Customer();
 89                 customer.setId(7);
 90                 customer.setUsername("zyk1");
 91                 customer.setJobs("student");
 92                 customer.setPhone("15614141855");
 93                 int row=sqlSession.update("com.itheima.po.Customer.updateCustomer", customer);
 94                 if(row>0) 
 95                     System.out.println("修改成功");
 96                 else 
 97                     System.out.println("修改失败");
 98                 
 99                 //注意要提交事务,增删改都涉及到事务
100                 sqlSession.commit();
101                 sqlSession.close();
102     
103     @Test
104     public void deleteCustomerTest() throws IOException 
105         //1.读取配置文件
106                 String resource="mybatis-config.xml";
107                 InputStream inputStream=Resources.getResourceAsStream(resource);
108                 //根据配置文件构建SqlSessionFactory
109                 SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
110                 //通过SqlSessionFactory创建sqlsession
111                 SqlSession sqlSession=sessionFactory.openSession();
112                 int row=sqlSession.delete("com.itheima.po.Customer.deleteCustomer", 3);
113                 if(row>0) 
114                     System.out.println("删除成功");
115                 else 
116                     System.out.println("删除失败");
117                 
118                 //注意要提交事务,增删改都涉及到事务
119                 sqlSession.commit();
120                 sqlSession.close();
121     
122     @Test
123     public void findAllUser() 
124          SqlSession sqlSession=MybatisUtils.getSqlSession();
125         List<User> users= sqlSession.selectList("com.itheima.po.User.findAllUser");
126         for(User user:users) 
127             System.out.println(user);
128         
129         sqlSession.close();
130     
131 

最下面的方法是学习<resultMap>标签所用的,上面的方法就是对t_customer表实现增删改查和现实的代码,其中第一个代码复用了MybatisUtils.java,后面的由于时间就没有。

Customer.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5  
 6  <!--namespace表示命名空间,唯一  -->
 7 <mapper namespace="com.itheima.po.Customer">
 8 <!--resultType是返回值,parameterType是传入值  -->
 9  <select id="findCustomerById" resultType="com.itheima.po.Customer" parameterType="Integer">
10  select * from t_customer where id = #id
11  </select>
12  <!-- 模糊查询 -->
13  <!--防止sql注入,不用$value,用#id可以  -->
14  <select id="findCustomerByName" resultType="com.itheima.po.Customer" parameterType="String">
15  select * from t_customer where username like concat(‘%‘,#username,‘%‘)
16  </select>
17  <insert id="addCustomer" parameterType="com.itheima.po.Customer">
18  insert into t_customer(username,jobs,phone)values(#username,#jobs,#phone)
19  </insert>
20  <update id="updateCustomer" parameterType="com.itheima.po.Customer" >
21  update t_customer set username=#username,jobs=#jobs,phone=#phone where id=#id
22  </update>
23  <delete id="deleteCustomer" parameterType="Integer">
24      delete  from t_customer where id=#id 
25  </delete>
26 </mapper>

mybatis-config.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4  "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6 <properties resource="db.properties"></properties>
 7 <!--配置环境,默认环境id为mysql  -->
 8  <environments default="mysql">
 9  <!--配置id为mysql的数据库环境  -->
10  <environment id="mysql">
11  <!--使用jdbc的事务管理  -->
12  <transactionManager type="JDBC"/>
13  <!--数据库连接池  -->
14  <dataSource type="POOLED">
15  <property name="driver" value="$jdbc.driver"/>
16  <property name="url" value="$jdbc.url"/>
17  <property name="username" value="$jdbc.username"/>
18  <property name="password" value="$jdbc.password"/>
19  </dataSource>
20  </environment>
21  </environments>
22  <!--可以配置多个mapper  -->
23  <mappers>
24  <mapper resource="com/itheima/po/CustomerMapper.xml"/>
25  <mapper resource="com/itheima/po/UserMapper.xml"/>
26  </mappers>
27 </configuration>

db.properties

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
3 jdbc.username=root
4 jdbc.password=123456

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# 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

mybatis-config中将<mapper resource="com/itheima/po/UserMapper.xml"/>删除

就可以实现mybatis基本的增删改查了。

package com.itheima.test;
import java.io.IOException;import java.io.InputStream;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 com.itheima.po.Customer;import com.itheima.po.User;import com.itheima.utils.MybatisUtils;
//mybatis入门程序测试
public class MybatisTest @Testpublic void findCustomerById() throws IOException ////1.读取配置文件//String resourceString="mybatis-config.xml";//InputStream inputStream=Resources.getResourceAsStream(resourceString);////根据配置文件构建SqlSessionFactory//SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);////通过SqlSessionFactory创建sqlsession//SqlSession sqlSession=sessionFactory.openSession();////sqlSession执行映射文件中的sql语句,并返回结果////第一个参数为mapper.xml中的id,第二个是传入的占位符就是#id的值 SqlSession sqlSession=MybatisUtils.getSqlSession();Customer customer=sqlSession.selectOne("com.itheima.po.Customer.findCustomerById", 1);System.out.println(customer.toString());//关闭sqlsessionsqlSession.close();@Testpublic void findCustomerByName() throws IOException //1.读取配置文件String resource="mybatis-config.xml";InputStream inputStream=Resources.getResourceAsStream(resource);//根据配置文件构建SqlSessionFactorySqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);//通过SqlSessionFactory创建sqlsessionSqlSession sqlSession=sessionFactory.openSession();List<Customer> customers= sqlSession.selectList("com.itheima.po.Customer.findCustomerByName","j");for (Customer customer:customers) System.out.println(customer.toString());sqlSession.close();@Testpublic void addCustomerTest() throws IOException //1.读取配置文件String resource="mybatis-config.xml";InputStream inputStream=Resources.getResourceAsStream(resource);//根据配置文件构建SqlSessionFactorySqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);//通过SqlSessionFactory创建sqlsessionSqlSession sqlSession=sessionFactory.openSession();Customer customer=new Customer();customer.setUsername("zyk");customer.setJobs("hero");customer.setPhone("15035766618");int row=sqlSession.insert("com.itheima.po.Customer.addCustomer", customer);if(row>0) System.out.println("插入了"+row+"数据");else System.out.println("插入失败");//注意要提交事务,增删改都涉及到事务sqlSession.commit();sqlSession.close();@Testpublic void updateCustomerTest() throws IOException //1.读取配置文件String resource="mybatis-config.xml";InputStream inputStream=Resources.getResourceAsStream(resource);//根据配置文件构建SqlSessionFactorySqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);//通过SqlSessionFactory创建sqlsessionSqlSession sqlSession=sessionFactory.openSession();Customer customer=new Customer();customer.setId(7);customer.setUsername("zyk1");customer.setJobs("student");customer.setPhone("15614141855");int row=sqlSession.update("com.itheima.po.Customer.updateCustomer", customer);if(row>0) System.out.println("修改成功");else System.out.println("修改失败");//注意要提交事务,增删改都涉及到事务sqlSession.commit();sqlSession.close();@Testpublic void deleteCustomerTest() throws IOException //1.读取配置文件String resource="mybatis-config.xml";InputStream inputStream=Resources.getResourceAsStream(resource);//根据配置文件构建SqlSessionFactorySqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);//通过SqlSessionFactory创建sqlsessionSqlSession sqlSession=sessionFactory.openSession();int row=sqlSession.delete("com.itheima.po.Customer.deleteCustomer", 3);if(row>0) System.out.println("删除成功");else System.out.println("删除失败");//注意要提交事务,增删改都涉及到事务sqlSession.commit();sqlSession.close();@Testpublic void findAllUser() SqlSession sqlSession=MybatisUtils.getSqlSession();List<User> users= sqlSession.selectList("com.itheima.po.User.findAllUser");for(User user:users) System.out.println(user);sqlSession.close();

 

以上是关于mybatis学习之普通增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis增删改查

mybatis怎么进行增删改查

mybatis增删改查

Mybatis学习 - CRUD操作(增删改查操作)

python学习之-员信息增删改查

Maven+Mybatis实现数据库增删改查