您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關利用mybatis怎么對數據庫進行增刪改查操作,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
所需要用到的其他工具或技術:
項目管理工具 : Maven
測試運行工具 : Junit
數據庫 : Derby
Maven Dependencies:
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.10.2.0</version> </dependency> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derbyclient</artifactId> <version>10.10.2.0</version> </dependency> </dependencies>
SQL 建表及數據插入(沿用前兩節中的數據庫表及數據):
CREATE TABLE USER_TEST_TB( ID INT PRIMARY KEY, USERNAME VARCHAR(20) NOT NULL, PASSWORD VARCHAR(20) NOT NULL, NICKNAME VARCHAR(20) NOT NULL ); INSERT INTO USER_TEST_TB VALUES(1,'1st','111','Jack'); INSERT INTO USER_TEST_TB VALUES(2,'2nd','222','Rose'); INSERT INTO USER_TEST_TB VALUES(3,'3rd','333','Will');
Mybatis配置文件 src/main/resource源目錄下
test-mybatis-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> <properties> <property name="driver" value="org.apache.derby.jdbc.ClientDriver" /> <property name="url" value="jdbc:derby://localhost:1527/bjpowernode;create=true" /> </properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/bjpowernode/practice/UserMapper.xml" / </mappers> </configuration>
User.java對象類(src/main/java/com/bjpowernode/practice目錄下)
package com.bjpowernode.practice; public class User { private Integer id; private String username; private String password; private String nickname; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } }
UserMapper.xml Mapper文件(src/main/java/com.bjpowernode.practice目錄下)
<?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.bjpowernode.practice.UserMapper"> <!-- 查詢 --> <select id="getUser" resultType="com.bjpowernode.practice.User"> select * from USER_TEST_TB </select> <!-- 插入 --> <insert id="insertUser"> insert into USER_TEST_TB values(#{id},#{username},#{password},#{nickname}) </insert> <!-- 更改 --> <update id="updateUser"> update USER_TEST_TB set USERNAME = #{username}, PASSWORD = #{password}, NICKNAME = #{nickname} where ID = #{id} </update> <!-- 刪除 --> <delete id="deleteUser"> delete from USER_TEST_TB WHERE ID=#{id} </delete> </mapper>
UserMapper.java Mapper類(src/main/java/com.bjpowernode.practice目錄下)
package com.bjpowernode.practice; import java.util.List; public interface UserMapper { public List<User> getUser(); public void insertUser(User user); public void updateUser(User user); public void deleteUser(int userId); }
測試類TestMyBatis.java(src/test/java/com.bjpowernode.practice目錄下)
package com.bjpowernode.practice; import java.io.InputStream; import java.text.MessageFormat; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; public class TestMyBatis { private String source; private InputStream inputStream; private SqlSessionFactory sqlSessionFactory; @Before public void setUp() { /** * 準備Mybatis運行環境 */ source = "test-mybatis-configuration.xml"; inputStream = TestMyBatis.class.getClassLoader().getResourceAsStream(source); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testGet() { try { // 獲取Session連接 SqlSession session = sqlSessionFactory.openSession(); // 獲取Mapper UserMapper userMapper = session.getMapper(UserMapper.class); // 顯示User信息 System.out.println("Test Get start..."); this.printUsers(userMapper.getUser()); System.out.println("Test Get finished..."); } catch (Exception e) { e.printStackTrace(); } } @Test public void testInsert() { try { // 獲取Session連接 SqlSession session = sqlSessionFactory.openSession(); // 獲取Mapper UserMapper userMapper = session.getMapper(UserMapper.class); System.out.println("Test insert start..."); // 顯示插入之前User信息 System.out.println("Before insert"); this.printUsers(userMapper.getUser()); // 執行插入 userMapper.insertUser(this.mockUser("FREU_INS_USER", "BJPOWERNODE_INS_PASS", "BJPOWERNODE_INS_NICK")); // 提交事務 session.commit(); // 顯示插入之后User信息 System.out.println("\r\nAfter insert"); this.printUsers(userMapper.getUser()); System.out.println("Test insert finished..."); } catch (Exception e) { e.printStackTrace(); } } @Test public void testUpdate() { try { // 獲取Session連接 SqlSession session = sqlSessionFactory.openSession(); // 獲取Mapper UserMapper userMapper = session.getMapper(UserMapper.class); System.out.println("Test update start..."); // 顯示更新之前User信息 System.out.println("Before update"); this.printUsers(userMapper.getUser()); // 執行更新 userMapper.updateUser(this.mockUser("FREU_UPD_USER", "BJPOWERNODE_UPD_PASS", "BJPOWERNODE_UPD_NICK")); // 提交事務 session.commit(); // 顯示更新之后User信息 System.out.println("\r\nAfter update"); this.printUsers(userMapper.getUser()); System.out.println("Test update finished..."); } catch (Exception e) { e.printStackTrace(); } } @Test public void testDelete() { try { // 獲取Session連接 SqlSession session = sqlSessionFactory.openSession(); // 獲取Mapper UserMapper userMapper = session.getMapper(UserMapper.class); System.out.println("Test delete start..."); // 顯示刪除之前User信息 System.out.println("Before delete"); this.printUsers(userMapper.getUser()); // 執行刪除 userMapper.deleteUser(this.mockUser(null, null, null).getId()); // 提交事務 session.commit(); // 顯示刪除之后User信息 System.out.println("\r\nAfter delete"); this.printUsers(userMapper.getUser()); System.out.println("Test delete finished..."); } catch (Exception e) { e.printStackTrace(); } } /** * * 組裝一個User對象 * * @return */ public User mockUser(String username, String password, String nickname) { User user = new User(); user.setId(10); user.setUsername(username); user.setPassword(password); user.setNickname(nickname); return user; } /** * * 打印用戶信息到控制臺 * * @param users */ private void printUsers(final List<User> users) { int count = 0; for (User user : users) { System.out.println(MessageFormat.format("==User[{0}]=================", ++count)); System.out.println("User Id: " + user.getId()); System.out.println("User UserName: " + user.getUsername()); System.out.println("User Password: " + user.getPassword()); System.out.println("User nickname: " + user.getNickname()); } } }
關于利用mybatis怎么對數據庫進行增刪改查操作就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。