MyBatis实现增删改查

Posted 大师兄丶2K

tags:

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

MyBatis是一个基于Java的持久层框架,专注是sql,需要我们程序员自己编写sql语句,sql的修改优化比较方便,Mybatis也是一个不完全的ORM框架,自己写sql,能够完成输入、输出映射。

应用场景:适用于需求变化比较多的项目

与hibernate比较:

Hibernate:是一个标准的ORM( 对象关系映射),入门超级简单,不用写sql语句,sql自动生成了。

  Hibernate:应用场景:适用于变化不多的大中小型项目,比如:OA(办公自动化)、CRM(客户关系管理)、后台管理系统…

 

环境准备:

  需要导入的jar文件,如下图:

还需要导入log4j.properties文件

1 log4j.rootLogger=DEBUG, stdout
2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
3 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
4 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

整个包和文件关系结构如图:

 

1.SqlMapConfig.xml

 1 <!DOCTYPE configuration
 2 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <configuration>
 5     <!-- 和spring整合后 environments配置将废除  mybatis-config.xml-->
 6     <environments default="development">
 7         <environment id="development">
 8         <!-- 使用jdbc事务管理-->
 9             <transactionManager type="JDBC" />
10         <!-- 数据库连接池-->
11             <dataSource type="POOLED">
12                 <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
13                 <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
14                 <property name="username" value="dsx" />
15                 <property name="password" value="admin" />
16             </dataSource>
17         </environment>
18     </environments>
19     
20     <!-- 加载mapper.xml -->
21     <mappers>
22     <!-- com.entity下面 
23         <mapper resource="com/entity/User.xml" />-->
24         <mapper resource="Book.xml" />
25     </mappers>
26     
27 </configuration>

2.Book实体类

 1 package com.test.book;
 2 
 3 import java.util.Date;
 4 
 5 /**
 6  * 
 7  * @author Mr
 8  * 图书实体类
 9  */
10 public class Book {
11     /*  INT PRIMARY KEY NOT NULL,
12       varchar2(100) default null,
13       DATE default null,
14       Number(8,2) default null*/
15     private int bookid;
16     private String bookname;
17     private Date bookdate;
18     private double bookprice;
19     public int getBookid() {
20         return bookid;
21     }
22     public void setBookid(int bookid) {
23         this.bookid = bookid;
24     }
25     public String getBookname() {
26         return bookname;
27     }
28     public void setBookname(String bookname) {
29         this.bookname = bookname;
30     }
31     public Date getBookdate() {
32         return bookdate;
33     }
34     public void setBookdate(Date bookdate) {
35         this.bookdate = bookdate;
36     }
37     public double getBookprice() {
38         return bookprice;
39     }
40     public void setBookprice(double bookprice) {
41         this.bookprice = bookprice;
42     }
43     public Book() {
44         super();
45         // TODO Auto-generated constructor stub
46     }
47     public Book( String bookname, Date bookdate, double bookprice) {
48         super();
49         this.bookname = bookname;
50         this.bookdate = bookdate;
51         this.bookprice = bookprice;
52     }
53     public Book(int bookid, String bookname, Date bookdate, double bookprice) {
54         super();
55         this.bookid = bookid;
56         this.bookname = bookname;
57         this.bookdate = bookdate;
58         this.bookprice = bookprice;
59     }
60     @Override
61     public String toString() {
62         return "Book的序号是:" + bookid + "\\r\\n书名是:" + bookname
63                 + "\\n图书出版日期是:" + bookdate + "\\n图书的价格是:" + bookprice + "]";
64     }
65     
66 }

3.book.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 <!-- namespace命名空间,为了对sql语句进行隔离,方便管理 ,mapper开发dao方式,使用namespace有特殊作用 -->
 6 <mapper namespace="test">
 7 <!-- 添加图书 -->
 8 <insert id="insertBook" parameterType="com.test.book.Book">
 9     INSERT INTO book VALUES(seq_book_id.nextval,#{bookname},#{bookdate},#{bookprice})
10 </insert>
11 <!-- 删除一本书 -->
12 <delete id="delBook" parameterType="java.lang.Integer">
13     DELETE book WHERE bookid=#{bookid}
14 </delete>
15 <!-- 更新一本图书 -->
16 <update id="upBook" parameterType="com.test.book.Book">
17     UPDATE book SET bookname=#{bookname},bookprice=#{bookprice} WHERE bookid=#{bookid}
18 </update>
19 <!-- 查询一本图书 -->
20 <select id="findBookById" parameterType="java.lang.Integer" resultType="com.test.book.Book">
21     SELECT * FROM book WHERE bookid=#{bookid}
22 </select>
23 <!-- 根据书名模糊查询 -->
24 <select id="findBookByName" parameterType="java.lang.String" resultType="com.test.book.Book">
25     SELECT * FROM book WHERE bookname LIKE \'%${value}%\'
26 </select>
27 
28 </mapper>

4.测试类Test1.java

 1 package com.test.test;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.Date;
 6 import java.util.List;
 7 
 8 import org.apache.ibatis.io.Resources;
 9 import org.apache.ibatis.session.SqlSession;
10 import org.apache.ibatis.session.SqlSessionFactory;
11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
12 
13 import com.test.book.Book;
14 
15 /**
16  * 
17  * @author Mr
18  * mybatis图书测试类
19  */
20 public class Test1 {
21 
22     public static void main(String[] args) {
23         try {
24             //找到mybatis文件并加载
25             String resource="SqlMapConfig.xml";
26             //读取这个文件
27             InputStream inputStream = Resources.getResourceAsStream(resource);
28             //创建sqlSessionFactory会话工厂
29             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
30             //操作数据库的sqlsession
31             SqlSession sqlSession = sqlSessionFactory.openSession();
32             
33     /*        //添加图书
34             Book book = new Book("MyBatis入门到精通", new Date(), 68.58);
35             sqlSession.insert("test.insertBook", book);
36             sqlSession.commit();*/
37             
38         /*    //删除一本图书
39             sqlSession.delete("test.delBook",2);
40             //提交事务
41             sqlSession.commit();*/
42             
43         /*    //更新一本图书
44             Book book = new Book();
45             book.setBookid(5);
46             book.setBookname("Linux从入门到精通");
47             book.setBookprice(59.45);
48             
49             sqlSession.update("test.upBook", book);
50             //提交事务
51             sqlSession.commit();*/
52             
53         /*    //查询一本书
54             Book book = sqlSession.selectOne("test.findBookById", 7);
55             System.out.println(book);*/
56             
57             //根据书名模糊查询
58             List<Book> list = sqlSession.selectList("test.findBookByName", "java");
59             for (Book book : list) {
60                 System.out.println(book);
61             }
62             
63             
64             //释放资源
65             sqlSession.close();
66             
67         } catch (IOException e) {
68             // TODO Auto-generated catch block
69             e.printStackTrace();
70         }finally{
71             System.out.println("\\n执行ok");
72         }
73 
74     }
75 
76 }

 欢迎交流学习,如有不足即使补充!

以上是关于MyBatis实现增删改查的主要内容,如果未能解决你的问题,请参考以下文章

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

mybatis怎么进行增删改查

[mybatis]快速搭建一个mybatis程序,实现对数据的增删改查

Mybatis增删改查

Mybatis实现增删改查

MyBatis基本例子-实现增删改查