程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Mybatis完成增刪改查(CRUD)實例代碼

Mybatis完成增刪改查(CRUD)實例代碼

編輯:關於JAVA

Mybatis完成增刪改查(CRUD)實例代碼。本站提示廣大學習愛好者:(Mybatis完成增刪改查(CRUD)實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是Mybatis完成增刪改查(CRUD)實例代碼正文


MyBatis簡介

MyBatis 是支撐通俗 SQL 查詢,存儲進程和高等映照的優良耐久層框架。 MyBatis 清除了簡直一切的 JDBC 代碼和參數的手工設置和對成果集的檢索。MyBatis 可使用簡略的XML 或注解用於設置裝備擺設和原始映照,將接口和 Java 的 POJO(Plain Old Java Objects,通俗的Java對象)映照成數據庫中的記載。

MyBatis下載:https://github.com/mybatis/mybatis-3/releases

Mybatis實例

對一個User表的CRUD操作:

User表:

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userAge` int(11) DEFAULT NULL,
`userAddress` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing'); 

在Src目次下建一個mybatis的xml設置裝備擺設文件Configuration.xml

<?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>
<!-- mybatis別號界說 -->
<typeAliases> 
<typeAlias alias="User" type="com.mybatis.test.User"/> 
</typeAliases> 
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" />
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<!-- mybatis的mapper文件,每一個xml設置裝備擺設文件對應一個接口 -->
<mappers>
<mapper resource="com/mybatis/test/User.xml"/>
</mappers>
</configuration> 

界說User mappers的User.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">
<mapper namespace="com.mybatis.test.IUserOperation">
<!-- select語句 -->
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where user.id = #{id}
</select>
<!-- 界說的resultMap,可以處理類的屬性名和數據庫列名紛歧致的成績-->
<!-- <resultMap type="User" id="userResultMap">
<id property="id" column="user_id" />
<result property="userName" column="user_userName" />
<result property="userAge" column="user_userAge" />
<result property="userAddress" column="user_userAddress" />
</resultMap> -->
<!-- 前往list的select語句,留意 resultMap的值是指向後面界說好的 -->
<!-- <select id="selectUsersByName" parameterType="string" resultMap="userResultMap">
select * from user where user.userName = #{userName}
</select> -->
<select id="selectUsersByName" parameterType="string" resultType="User">
select * from user where user.userName = #{userName}
</select>
<!--履行增長操作的SQL語句。id和parameterType分離與IUserOperation接口中的addUser辦法的名字和參數類型分歧。
useGeneratedKeys設置為"true"注解要MyBatis獲得由數據庫主動生成的主鍵;keyProperty="id"指定把獲得到的主鍵值注入到User的id屬性--> 
<insert id="addUser" parameterType="User" 
useGeneratedKeys="true" keyProperty="id"> 
insert into user(userName,userAge,userAddress) 
values(#{userName},#{userAge},#{userAddress}) 
</insert>
<update id="updateUser" parameterType="User" >
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper> 

設置裝備擺設文件完成了接口和SQL語句的映照關系。selectUsersByName采取了2種方法完成,正文失落的也是一種完成,采取resultMap可以把屬性和數據庫列名映照關系界說好,property為類的屬性,column是表的列名,也能夠是表列名的別號!

User類的界說:

package com.mybatis.test;
public class User {
private int id;
private String userName;
private int userAge;
private String userAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
@Override
public String toString(){
return this.userName+" "+this.userAge+" "+this.userAddress;
}
}

IUserOperaton界說:

package com.mybatis.test;
import java.util.List;
public interface IUserOperation {
public User selectUserByID(int id);
public List<User> selectUsersByName(String userName);
public void addUser(User user);
public void updateUser(User user);
public void deleteUser(int id);
} 

IUserOperation為操作接口,函數名和mybatis的xml設置裝備擺設文件中的操作id名對應。

測試類Test:

package com.mybatis.test;
import java.io.Reader;
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;
public class Test {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public void getUserByID(int userID) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
User user = userOperation.selectUserByID(userID);
if (user != null) {
System.out.println(user.getId() + ":" + user.getUserName()
+ ":" + user.getUserAddress());
}
} finally {
session.close();
}
}
public void getUserList(String userName) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
List<User> users = userOperation.selectUsersByName(userName);
for (User user : users) {
System.out.println(user.getId() + ":" + user.getUserName()
+ ":" + user.getUserAddress());
}
} finally {
session.close();
}
}
/**
* 增長後要commit
*/
public void addUser() {
User user = new User();
user.setUserAddress("place");
user.setUserName("test_add");
user.setUserAge(30);
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
userOperation.addUser(user);
session.commit();
System.out.println("新增用戶ID:" + user.getId());
} finally {
session.close();
}
}
/**
* 修正後要commit
*/
public void updateUser() {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
User user = userOperation.selectUserByID(1);
if (user != null) {
user.setUserAddress("A new place");
userOperation.updateUser(user);
session.commit();
}
} finally {
session.close();
}
}
/**
* 刪除後要commit.
* 
* @param id
*/
public void deleteUser(int id) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session
.getMapper(IUserOperation.class);
userOperation.deleteUser(id);
session.commit();
} finally {
session.close();
}
}
public static void main(String[] args) {
try {
Test test = new Test();
// test.getUserByID(1);
// test.getUserList("test1");
// test.addUser();
// test.updateUser();
// test.deleteUser(6);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

以上所述是小編給年夜家引見的Mybatis完成增刪改查(CRUD)實例代碼 ,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved