使用MyBatis進行對資料表的增刪改查操作
1.匯入jar包並配置MyBatis的配置檔案
<?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>
<!--
default="development":指定當前環境的模式,只有兩個取值:
development: 開發模式
worker:工作模式
-->
<environments default="development">
<!--
id="development":指定當前的環境模式,只需要注意的是:當前id的取值必須和environments節點中default的取值相同
-->
<environment id="development">
<!-- type="JDBC":指定當前的事務管理器為JDBC,大小寫不敏感 -->
<transactionManager type="JDBC"/>
<!--
type="POOLED":指定當前資料來源的型別為連線池型別
-->
<dataSource type="POOLED">
<!-- 資料庫連線資訊 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/>
<property name="password" value="zxczxc"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 註冊自定義的對映檔案 -->
<mapper resource="com/gu/domain/Person.cfg.xml"/>
</mappers>
</configuration>
2.建立實體類,並配置對映檔案
package com.gu.domain;
import java.util.Date;
public class Person {
private Integer id;
private String name;
private Integer age;
private String sex;
private Date birthday;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, Integer age, String sex, Date birthday) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
}
public Person(Integer id, String name, Integer age, String sex,
Date birthday) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
}
Setter、Getter方法(省略)。。。
@Override
public String toString() {
return "Person [age=" + age + ", birthday=" + birthday + ", id=" + id
+ ", name=" + name + ", sex=" + sex + "]";
}
}
在以上的配置檔案中,不管使用者是進行對資料表的和中操作都要配置的,所以將以上兩步提取出來,現分別對增刪改查進行詳細說明。
(1)插入資料操作
MyBatis是一個ORM框架,是一個基於JDBC的開源框架.其中資料庫和相關表必須手工建立。
1、建立資料庫以及資料表
create database test;
create table t_person(
id int primary key auto_increment,
name varchar(20) unique not null,
age int ,
sex varchar(10) ,
birthday date
);
2<?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">
<mapper namespace="com.gu.domain.PersonMapper">
<insert id="insertPerson" parameterType="com.gu.domain.Person">
insert into t_person values(null,#{name},#{age},#{sex},#{birthday});
</insert>
</mapper>
說明:namespace="com.gu.domain.PersonMapper" :取值必須唯一,一般建議使用包名+類名
paramentType="com.gu.domain.Person":指定輸入引數的資料型別(因為此處我們是插入一個person實體,所以用Person實體類)
resultType="com.gu.domain.Person":指定輸出引數的資料型別(只插入無輸出情況,所以此處省略不寫)
id=”insertPerson” :此處是insert語句的片段,並且id值必須唯一。命名要有規範!
#{ } :表示MyBatis特有的規範寫法,使用在xml對映檔案中。{ } 內填寫與之對應的屬性名。如果輸入引數的資料型別(parameterType)是“int”型別的,{ }內可以任意填寫,其餘則不行。
3、測試類
public class test01 {
public static void main(String[] args) {
String resource = "myBatis.cfg.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Person person = new Person("趙麗穎", 17, "女",new Date());
int count= sqlSession.insert("com.gu.domain.PersonMapper.insertPerson",person); sqlSession.commit();
System.out.println("count="+count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
說明:
· 如何構建SqlSessionFactory?
從 XML 中構建 SqlSessionFactory步驟:
//1.得到輸入流
String resource = "myBatis.cfg.xml";
inputStream=Resources.getResourceAsStream(resource);
//2.得到SqlSessionFactory物件
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//3.得到SqlSession物件
//sqlSession=sqlSessionFactory.openSession();//預設事務不是自動提交的
sqlSession=sqlSessionFactory.openSession(true);//設定事務自動提交,則不需要手工提交事務了
·使用sqlSession.insert(statement,parameter)進行資料插入操作。
Statement:namespace+id的值(如:com.gu.domain.PersonMapper.insertPerson)
Parameter:傳入的屬性值(如:person)
·在進行資料增刪改時,必須手動進行事務提交才能在資料表中儲存資料。所以在sqlSession.insert()方法後還需要手動的事務提交。事務提交呼叫sqlSession.commit()方法。
(2)檢視資料操作
1、對映檔案配置資訊<?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">
<mapper namespace="com.gu.domain.PersonMapper">
<select id="selectById" parameterType="int" resultType="com.gu.domain.Person">
select *from t_person where id = #{id} ; <!-- 根據id進行查詢 -->
</select>
<select id="selectAll" resultType="com.gu.domain.Person">
select * from t_person ; <!—查詢所有 -->
</select>
<select id="selectLike" parameterType="string" resultType="com.gu.domain.Person">
<!-- select * from t_person where name like #{name};-->
select * from t_person where name like #{conditon}; <!—- 模糊查詢 -->
</select>
</mapper>
2、測試
public class test01 {
public static void main(String[] args) {
String resource = "myBatis.cfg.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Person person =
sqlSession.selectOne("com.gu.domain.PersonMapper.selectById",1);
/*
* List<Person> persons
* =sqlSession.selectList("com.gu.domain.PersonMapper.selectAll");
* System.out.println(persons);
*/
/*String condition = "趙";
List<Person> person = sqlSession.selectList(
"com.gu.domain.PersonMapper.selectLike",
'%' + condition + '%');
System.out.println(person);*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注意:
(1)selectOne和selectList 都可以查詢到使用者,但是兩者有明顯的區別:
SelectOne : 表示查詢的使用者是一個或者是0;
SelectList :表示查詢的使用者是1個或者多個,返回的是list集合。
當對 物件進行查詢時,必須使用SelectList方法。
(2) 在模糊查詢時,Parameter傳入的屬性值要根據對映檔案的模糊查詢條件進行給定。模糊查詢可能查出1個或者多個,所以說模糊查詢必須使用selectList方法,返回List集合。
(3)修改資料操作
1、對映檔案配置資訊
<?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">
<mapper namespace="com.gu.domain.PersonMapper">
<update id="updateById" parameterType="com.gu.domain.Person">
update t_person set name=#{name},age=#{age},sex=#{sex},birthday=#{birthday}
where id=#{id};
</update>
</mapper>
2、測試(先查詢此使用者是否存在,如果存在則進行修改使用者資訊)
public class test01 {
public static void main(String[] args) {
String resource = "myBatis.cfg.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.selectOne("com.gu.domain.PersonMapper.selectById", 5);
if(person!=null){
person.setName("王思聰");
person.setAge(28);
person.setSex("女");
person.setBirthday(new Date());
sqlSession.update("com.gu.domain.PersonMapper.updateById",person);
sqlSession.commit();
}else{
throw new RuntimeException("查不到此使用者");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
說明:對用進行修改資訊時,使用update語句。
(4)刪除資料操作
1、對映檔案配置資訊
<?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">
<mapper namespace="com.gu.domain.PersonMapper">
<delete id="deleteAll"> <!— 刪除所有 -->
delete from t_person;
</delete>
</mapper>
2、測試
public class test01 {
public static void main(String[] args) {
String resource = "myBatis.cfg.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int count=sqlSession.delete("com.gu.domain.PersonMapper.deleteAll");
sqlSession.commit();
System.out.println("coune="+count);
} catch (IOException e) {
e.printStackTrace();
}
}
}
說明:刪除操作時,直接呼叫delete方法。