欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

簡(jiǎn)述Mybatis增刪改查實(shí)例代碼

 更新時(shí)間:2016年10月24日 09:52:23   作者:suwu150  
本文給大家分享編寫一個(gè)簡(jiǎn)單的mybatis進(jìn)行插入數(shù)據(jù)的實(shí)例代碼,非常不錯(cuò)具有參考借鑒價(jià)值,感興趣的朋友一起看看吧

編寫一個(gè)簡(jiǎn)單的mybatis進(jìn)行插入數(shù)據(jù)的實(shí)例

1 數(shù)據(jù)庫(kù)建表 其中建表dob=Date of Birth 的意思

create table students 
(stud_id number primary key, 
name varchar2(20), 
email varchar2(20), 
dob date 
);

Oracle數(shù)據(jù)庫(kù)中出現(xiàn)表已創(chuàng)建,則表示創(chuàng)建成功,如果出現(xiàn)名稱已被使用,則可在建表之前進(jìn)行刪除操作:drop table students;或者進(jìn)行級(jí)聯(lián)刪除drop table students cascade constraints;然后再重新創(chuàng)建

2 新建一個(gè)項(xiàng)目

2.1 創(chuàng)建好相應(yīng)的package及class,其中Student是我們要進(jìn)行插入的對(duì)象,由于數(shù)據(jù)類型和數(shù)據(jù)庫(kù)中的值進(jìn)行了對(duì)應(yīng),因此我們能夠進(jìn)行將一整個(gè)對(duì)象進(jìn)行插入,因此我們使用pojo類進(jìn)行封裝對(duì)象

package com.mybatis.pojo; 
import java.util.Date; 
public class Student { 
private Integer studId; 
private String name; 
private String email; 
private Date dob; 
public Student() {}//注意無(wú)參的構(gòu)造器 
public Student(Integer studId, String name, String email, Date dob) { 
this.studId = studId; 
this.name = name; 
this.email = email; 
this.dob = dob; 
} 
public Integer getStudId() { 
return studId; 
} 
public void setStudId(Integer studId) { 
this.studId = studId; 
} 
public String getName() { 
return name; 
} 
public void setName(String name) { 
this.name = name; 
} 
public String getEmail() { 
return email; 
} 
public void setEmail(String email) { 
this.email = email; 
} 
public Date getDob() { 
return dob; 
} 
public void setDob(Date dob) { 
this.dob = dob; 
} 
@Override 
public String toString() { 
return "Student [studId=" + studId + ", name=" + name + ", email=" 
+ email + ", dob=" + dob + "]"; 
} 
}

3 項(xiàng)目中引入mybatis的核心包以及可選的依賴包

文件下載:mybatis包下載

最新版下載:https://github.com/mybatis/mybatis-3/releases

必須的包 mybatis-3.3.0.jar ojdbc14.jar

可選的包 junit-4.7.jar log4j-1.2.17.jar

其中mybatis-3.3.0.jar 用于實(shí)現(xiàn)mybatis提供的功能,ojdbc14.jar用于連接數(shù)據(jù)庫(kù),junit-4.7.jar用于實(shí)現(xiàn)功能測(cè)試,log4j-1.2.17.jar用于進(jìn)行日志記錄

如下圖所示:在項(xiàng)目目錄下建立一個(gè)新的文件夾jar,將需要導(dǎo)入的包進(jìn)行復(fù)制粘貼到j(luò)ar目錄下邊

注意:在本地存放這些jar包時(shí)不要使用中文

然后再右鍵選中jar目錄下的四個(gè)文件,點(diǎn)擊添加“buildPath->add Path”,就能夠看到如下界面:表示添加路徑成功

4 項(xiàng)目中引入mybatis配置文件dtd約束文件

同樣的,在項(xiàng)目下新建dtd目錄,將約束文件復(fù)制到目錄下即可,如下圖所示:dtd文件結(jié)構(gòu),dtd文件下載:

http://download.csdn.net/download/suwu150/9660699

dtd文件的作用是對(duì)配置文件xml進(jìn)行約束,這樣的話程序員就能按照規(guī)范書寫xml文件,mybatis就能夠正確的讀取并解析,以上dtd是配置本地的,當(dāng)然我們也能夠使用官網(wǎng)的連接進(jìn)行約束

5 mybatis中的配置文件和映射文件分別引入到項(xiàng)目中

1) src下面的mybatis-config.xml:

首先我們對(duì)本地dtd約束進(jìn)行關(guān)聯(lián),如下圖進(jìn)入到Preferences下面,在搜索框中輸入xml,選中xml catalog配置名,然后點(diǎn)擊右邊的add按鈕

出現(xiàn)如下圖所示界面,其中Location位置和key位置為空,下圖是配置過(guò)的,key內(nèi)容為-//mybatis.org//DTD Config 3.0//EN,Location內(nèi)容為自己的,可以通過(guò)Workspace進(jìn)行選擇,也就是我們前面復(fù)制到項(xiàng)目中的dtd文件(第4步操作中的):

點(diǎn)擊OK,現(xiàn)在我們能夠進(jìn)行xml配置文件的書寫,添加約束的作用就是對(duì)程序員的書寫進(jìn)行規(guī)范,以保證mybatis能夠正常解析

如下圖所示:選中src右鍵創(chuàng)建新文件mybatis-config.xml

注意:xml文件開(kāi)頭必須置頂,前面不能有空格

<?xml version="1.0" encoding="UTF-8"?> 
<!-- 進(jìn)行dtd約束,其中-//mybatis.org//DTD Config 3.0//EN為公共約束, 
http://mybatis.org/dtd/mybatis-3-config.dtd為獲取網(wǎng)絡(luò)中提供的dtd約束 --> 
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration> 
<typeAliases> 
<!-- 給pojo類起別名 --> 
<typeAlias type="com.mybatis.pojo.Student" alias="Student" /> 
</typeAliases> 
<!-- 配置數(shù)據(jù)庫(kù)環(huán)境其中development為默認(rèn)的數(shù)據(jù)庫(kù)名稱事務(wù)管理器transactionManager類型為JDBC類型,數(shù)據(jù)源dataSource使用連接池的方式 --> 
<environments default="development"> 
<environment id="development"> 
<transactionManager type="JDBC"></transactionManager> 
<dataSource type="POOLED"> 
<!-- 配置數(shù)據(jù)庫(kù)信息這里使用oracle數(shù)據(jù)庫(kù) --> 
<property name="driver" value="oracle.jdbc.driver.OracleDriver" /> 
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> 
<property name="username" value="briup" /> 
<property name="password" value="briup" /> 
</dataSource> 
</environment> 
</environments> 
<!-- 配置xml文件映射路徑,在這里可以進(jìn)行sql的操作 --> 
<mappers> 
<mapper resource="com/mybatis/mappers/StudentMapper.xml" /> 
</mappers> 
</configuration>

2)com.mybatis.mappers包下面的StudentMapper.xml:

首先,我們實(shí)現(xiàn)接口com.mybatis.mappers;包下面新建一個(gè)接口StudentMapper.Java,用來(lái)對(duì)應(yīng)xml文件中的sql語(yǔ)句(映射),從而方便我們調(diào)用

package com.mybatis.mappers; 
import java.util.List; 
import com.mybatis.pojo.Student; 
public interface StudentMapper { 
List<Student> findAllStudents(); 
Student findStudentById(Integer id); 
void insertStudent(Student student); 
}

使用同樣的方法,對(duì)mapper文件進(jìn)行約束

然后進(jìn)行xml代碼的編寫:

<?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"> 
<!-- com.mybatis.mappers.StudentMapper是我們定義接口的全限定名字 這樣就可以使用接口調(diào)用映射的SQL語(yǔ)句了 這個(gè)名字一定要和接口對(duì)應(yīng)上 --> 
<mapper namespace="com.mybatis.mappers.StudentMapper"> 
<resultMap type="Student" id="StudentResult"> 
<id property="studId" column="stud_id" /> 
<result property="name" column="name" /> 
<result property="email" column="email" /> 
<result property="dob" column="dob" /> 
</resultMap> 
<select id="findAllStudents" resultMap="StudentResult"> 
SELECT * FROM STUDENTS 
</select> 
<!-- 列名和屬性名字不一致可以給查詢的列起一個(gè)別名 --> 
<select id="findStudentById" parameterType="int" resultType="Student"> 
SELECT STUD_ID AS STUDID,NAME,EMAIL,DOB 
FROM STUDENTS 
WHERE 
STUD_ID=#{id} 
</select> 
<insert id="insertStudent" parameterType="Student"> 
INSERT INTO 
STUDENTS(STUD_ID,NAME,EMAIL,DOB) 
VALUES(#{studId},#{name},#{email},#{dob}) 
</insert> 
</mapper>

*******************************************************
注意:xml文件中寫的sql語(yǔ)句,最后面不要寫分號(hào),否則會(huì)報(bào)錯(cuò)誤,ORA-00911: 無(wú)效字符

*******************************************************

6 配置log4j.properties文件中的日志輸出:

位置src下面,文件名log4j.properties

內(nèi)容:

log4j.rootLogger=DEBUG, stdout 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n 
#show sql 
log4j.logger.java.sql.ResultSet=INFO 
log4j.logger.org.apache=INFO 
log4j.logger.java.sql.Connection=DEBUG 
log4j.logger.java.sql.Statement=DEBUG 
log4j.logger.java.sql.PreparedStatement=DEBUG

7 創(chuàng)建一個(gè)測(cè)試類StudentMapperTest.java

package com.mybatis.test; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.Date; 
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.mybatis.mappers.StudentMapper; 
import com.mybatis.pojo.Student; 
public class StudentMapperTest { 
@Test 
public void test_insertStudent() 
{ 
SqlSession session=null; 
try { 
// 獲取配置文件 
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 
// 生成工廠對(duì)象 
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
// 使用工廠對(duì)象生成sqlsession 
session = sqlSessionFactory.openSession(); 
// 使用sqlsession獲得映射接口的實(shí)現(xiàn)類對(duì)象,接口的引用指向?qū)崿F(xiàn)類的對(duì)象 
StudentMapper studentMapper = session.getMapper(StudentMapper.class); 
Student student = new Student(1, "suwu150", "1730@qq.com",new Date()); 
studentMapper.insertStudent(student); 
} catch (IOException e) { 
session.rollback(); 
e.printStackTrace(); 
} 
} 
}

8 運(yùn)行成功后會(huì)在控制臺(tái)中看到log4j日志輸出的這個(gè)程序運(yùn)行的相關(guān)信息,如下:

在數(shù)據(jù)庫(kù)中查詢能夠看到如下信息

9 對(duì)mybatis的一些基本封裝

每次讀取配置文件,產(chǎn)生一個(gè)工廠對(duì)象SqlSessionFactory,然后再生成出SqlSession對(duì)象,這個(gè)過(guò)程雖然并不復(fù)雜,但是也都是一些重復(fù)的代碼流程,所以我們可以對(duì)其進(jìn)行一個(gè)簡(jiǎn)單的封裝:

package com.mybatis.utils; 
import java.io.IOException; 
import java.io.InputStream; 
import org.apache.ibatis.io.Resources; 
import org.apache.ibatis.session.SqlSession; 
import org.apache.ibatis.session.SqlSessionFactory; 
import org.apache.ibatis.session.SqlSessionFactoryBuilder; 
public class MyBatisSqlSessionFactory { 
private static SqlSessionFactory sqlSessionFactory; 
public static SqlSessionFactory getSqlSessionFactory(){ 
if(sqlSessionFactory == null){ 
InputStream inputStream = null; 
try { 
inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
} catch (IOException e) { 
e.printStackTrace(); 
throw new RuntimeException(e.getCause()); 
} 
} 
return sqlSessionFactory; 
} 
public static SqlSession openSession() { 
return openSession(false); //默認(rèn)手動(dòng)提交,故我們?cè)谡{(diào)用的時(shí)候需要進(jìn)行提交 
} 
public static SqlSession openSession(boolean autoCommit) { 
return getSqlSessionFactory().openSession(autoCommit); 
} 
} 

之后每次使用的時(shí)候只需要調(diào)用該類中的靜態(tài)方法openSession即可

上面的代碼可簡(jiǎn)寫為: //注意事務(wù)是自動(dòng)提交還是手動(dòng)提交

MyBatisSqlSessionFactory.openSession().getMapper(StudentMapper.class).insertStudent(s);

10 在上面的測(cè)試中,我們僅僅完成了增加的功能,下面我們進(jìn)行實(shí)現(xiàn)刪除修改和查詢的功能:

在映射文件中進(jì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"> 
<!-- com.mybatis.mappers.StudentMapper是我們定義接口的全限定名字 這樣就可以使用接口調(diào)用映射的SQL語(yǔ)句了 這個(gè)名字一定要和接口對(duì)應(yīng)上 --> 
<mapper namespace="com.mybatis.mappers.StudentMapper"> 
<resultMap type="Student" id="StudentResult"> 
<id property="studId" column="stud_id" /> 
<result property="name" column="name" /> 
<result property="email" column="email" /> 
<result property="dob" column="dob" /> 
</resultMap> 
<select id="findAllStudents" resultMap="StudentResult"> 
SELECT * FROM STUDENTS 
</select> 
<!-- 列名和屬性名字不一致可以給查詢的列起一個(gè)別名 --> 
<select id="findStudentById" parameterType="int" resultType="Student"> 
SELECT STUD_ID AS STUDID,NAME,EMAIL,DOB 
FROM STUDENTS 
WHERE 
STUD_ID=#{id} 
</select> 
<insert id="insertStudent" parameterType="Student"> 
INSERT INTO 
STUDENTS(STUD_ID,NAME,EMAIL,DOB) 
VALUES(#{studId},#{name},#{email},#{dob}) 
</insert> 
<delete id="deleteStudentById" parameterType="int"> 
delete from students 
where STUD_ID=#{id} 
</delete> 
<update id="updateStudentById" parameterType="Student"> 
update students 
set name=#{name},email=#{email} 
where stud_id=#{studId} 
</update> 
</mapper>

在接口類中進(jìn)行如下配置:

package com.mybatis.mappers; 
import java.util.List; 
import com.mybatis.pojo.Student; 
public interface StudentMapper { 
List<Student> findAllStudents(); 
Student findStudentById(Integer id); 
void insertStudent(Student student); 
void deleteStudentById(Integer id); 
void updateStudentById(Student student); 
}

在測(cè)試文件中編寫如下代碼:

package com.mybatis.test; 
import java.io.IOException; 
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 com.mybatis.mappers.StudentMapper; 
import com.mybatis.pojo.Student; 
import com.mybatis.utils.MyBatisSqlSessionFactory; 
public class StudentMapperTest { 
@Test 
public void test_insertStudent() 
{ 
SqlSession session=null; 
try { 
// 獲取配置文件 
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 
// 生成工廠對(duì)象 
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
// 使用工廠對(duì)象生成sqlsession 
session = sqlSessionFactory.openSession(); 
// 使用sqlsession獲得映射接口的實(shí)現(xiàn)類對(duì)象,接口的引用指向?qū)崿F(xiàn)類的對(duì)象 
StudentMapper studentMapper = session.getMapper(StudentMapper.class); 
Student student = new Student(2, "suwu150", "1730@qq.com",new Date()); 
studentMapper.insertStudent(student); 
session.commit(); 
System.out.println("執(zhí)行完畢"); 
} catch (IOException e) { 
session.rollback(); 
e.printStackTrace(); 
} 
} 
@Test 
public void test_deleteStudentById() 
{ 
SqlSession session=null; 
session = MyBatisSqlSessionFactory.openSession();//使用封裝之后的類 
// 使用sqlsession獲得映射接口的實(shí)現(xiàn)類對(duì)象,接口的引用指向?qū)崿F(xiàn)類的對(duì)象 
StudentMapper studentMapper = session.getMapper(StudentMapper.class); 
studentMapper.deleteStudentById(2); 
session.commit(); 
System.out.println("執(zhí)行完畢"); 
} 
@Test 
public void test_updateStudentById() 
{ 
SqlSession session=null; 
session = MyBatisSqlSessionFactory.openSession();//使用封裝之后的類 
// 使用sqlsession獲得映射接口的實(shí)現(xiàn)類對(duì)象,接口的引用指向?qū)崿F(xiàn)類的對(duì)象 
StudentMapper studentMapper = session.getMapper(StudentMapper.class); 
Student student = new Student(); 
student.setStudId(1); 
student.setName("sususu"); 
student.setEmail("123443@136.com"); 
studentMapper.updateStudentById(student); 
session.commit(); 
System.out.println("執(zhí)行完畢"); 
} 
@Test 
public void test_findStudentById() 
{ 
SqlSession session=null; 
session = MyBatisSqlSessionFactory.openSession();//使用封裝之后的類 
// 使用sqlsession獲得映射接口的實(shí)現(xiàn)類對(duì)象,接口的引用指向?qū)崿F(xiàn)類的對(duì)象 
StudentMapper studentMapper = session.getMapper(StudentMapper.class); 
Student student = studentMapper.findStudentById(1); 
System.out.println(student); 
System.out.println("執(zhí)行完畢"); 
} 
@Test 
public void test_findAllStudents() 
{ 
SqlSession session=null; 
session = MyBatisSqlSessionFactory.openSession();//使用封裝之后的類 
// 使用sqlsession獲得映射接口的實(shí)現(xiàn)類對(duì)象,接口的引用指向?qū)崿F(xiàn)類的對(duì)象 
StudentMapper studentMapper = session.getMapper(StudentMapper.class); 
List<Student> list = studentMapper.findAllStudents(); 
System.out.println(list); 
System.out.println("執(zhí)行完畢"); 
} 
}

這樣我們就完成了對(duì)Student對(duì)象的增刪改查

以上所述是小編給大家介紹的Mybatis增刪改查實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 一篇文章帶你深入了解Java線程池

    一篇文章帶你深入了解Java線程池

    這篇文章主要介紹了Java 線程池的相關(guān)資料,文中講解非常細(xì)致,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下,希望能給你帶來(lái)幫助
    2021-08-08
  • 使用dubbo+zookeeper+spring boot構(gòu)建服務(wù)的方法詳解

    使用dubbo+zookeeper+spring boot構(gòu)建服務(wù)的方法詳解

    這篇文章主要給大家介紹了關(guān)于如何使用dubbo+zookeeper+spring boot構(gòu)建服務(wù)的相關(guān)資料,文中通過(guò)示例代碼及圖片介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • java實(shí)現(xiàn)2048小游戲(含注釋)

    java實(shí)現(xiàn)2048小游戲(含注釋)

    這篇文章主要為大家介紹了java實(shí)現(xiàn)2048小游戲,含詳細(xì)注釋,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • IDEA如何配置本地tomcat啟動(dòng)項(xiàng)目

    IDEA如何配置本地tomcat啟動(dòng)項(xiàng)目

    這篇文章主要介紹了IDEA如何配置本地tomcat啟動(dòng)項(xiàng)目問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • 詳解Java實(shí)現(xiàn)分治算法

    詳解Java實(shí)現(xiàn)分治算法

    分治算法(divide and conquer)是五大常用算法(分治算法、動(dòng)態(tài)規(guī)劃算法、貪心算法、回溯法、分治界限法)之一,很多人在平時(shí)學(xué)習(xí)中可能只是知道分治算法,但是可能并沒(méi)有系統(tǒng)的學(xué)習(xí)分治算法,本篇就帶你較為全面的去認(rèn)識(shí)和了解分治算法
    2021-06-06
  • Java實(shí)現(xiàn)鼠標(biāo)拖拽移動(dòng)界面組件

    Java實(shí)現(xiàn)鼠標(biāo)拖拽移動(dòng)界面組件

    在Java中,F(xiàn)rame或者JFrame自身已經(jīng)實(shí)現(xiàn)了鼠標(biāo)拖拽標(biāo)題欄移動(dòng)窗口的功能。但是Jframe的樣式實(shí)在無(wú)法令人滿意,那你又該怎么實(shí)現(xiàn)鼠標(biāo)拖拽移動(dòng)窗口的目的呢?今天我們來(lái)探討下
    2014-09-09
  • Spring Security OAuth2實(shí)現(xiàn)使用JWT的示例代碼

    Spring Security OAuth2實(shí)現(xiàn)使用JWT的示例代碼

    這篇文章主要介紹了Spring Security OAuth2實(shí)現(xiàn)使用JWT的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-09-09
  • 詳解Mybatis模板(已優(yōu)化)適合小白

    詳解Mybatis模板(已優(yōu)化)適合小白

    這篇文章主要介紹了Mybatis模板(已優(yōu)化)適合小白,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • Springboot整合Shiro之加鹽MD5加密的方法

    Springboot整合Shiro之加鹽MD5加密的方法

    這篇文章主要介紹了Springboot整合Shiro之加鹽MD5加密的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-12-12
  • springmvc與mybatis集成配置實(shí)例詳解

    springmvc與mybatis集成配置實(shí)例詳解

    這篇文章主要介紹了springmvc與mybatis集成配置實(shí)例詳解的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-09-09

最新評(píng)論