您好,登錄后才能下訂單哦!
這篇文章主要介紹“Mybatis怎么實現一個增刪改查程序”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Mybatis怎么實現一個增刪改查程序”文章能幫助大家解決問題。
1.idea新建Maven項目Mybatis-study 將項目里的src文件夾刪掉 依次將此項目作為父項目
2.在Mybatis-study中新建模塊mybatis-01
在mybatis的pom文件中可以看到其父項目為ybatis-study
<parent>
<artifactId>MyBatis-study</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
3. 在Mybatis-study的pom.xml中引入如下jar包
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.29</version> </dependency> </dependencies>
4.將IDEA和MySQL數據庫建立連接:
根據實際情況填寫user和password 填寫之后點擊Test Connection
測試成功之后點擊Schemas選擇你要鏈接的數據庫
5.新建mybatis-config.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/smbms?useSSL=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/kero/dao/UserMapper.xml" /> </mappers> </configuration>
6.創建實體類User 注意:實體類中成員變量名要和數據庫表中字段名完全一致
package com.kero.pojo; public class User { private int id; private String name; private String password; public User() { } public User(int id, String name, String password) { this.id = id; this.name = name; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getpassword() { return password; } public void setpassword(String pwd) { this.password = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + password + '\'' + '}'; } }
7.編寫工具類Utils
package com.kero.utils; 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 java.io.IOException; import java.io.InputStream; //sqlSessionFactory public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mybatis第一步 獲取sqlSessionFactory對象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { throw new RuntimeException(e); } } /* 既然有了 SqlSessionFactory,顧名思義,我們可以從中獲得 SqlSession 的實例。SqlSession 提供了在數據庫執行 SQL 命令所需的所有方法。你可以通過 SqlSession 實例來直接執行已映射的 SQL 語句。例如: */ public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
8.定義接口
package com.kero.dao; import com.kero.pojo.User; import java.util.List; public interface UserMapper { //查詢全部用戶 List<User> getUserList(); //根據ID查詢用戶 User getUserByID(int id); //insert一個用戶 int addUser(User user); //修改一個用戶 int updateUser(User user); //刪除一個用戶 int deleteUser(int id); }
9.定義Mapper文件 這里的Mapper文件相當于原來傳統方式中接口的實現類
<?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"> <!--namespace會綁定一個對應的Mapper接口--> <mapper namespace="com.kero.dao.UserMapper"> <select id="getUserList" resultType="com.kero.pojo.User"> select * from smbms.user </select> <select id="getUserByID" parameterType="int" resultType="com.kero.pojo.User"> select * from smbms.user where id = #{id} </select> <insert id="addUser" parameterType="com.kero.pojo.User"> insert into smbms.user (id, name, password) VALUES (#{id},#{name},#{password}) </insert> <update id="updateUser" parameterType="com.kero.pojo.User"> update smbms.user set name=#{name},password=#{password} where id = #{id} </update> <delete id="deleteUser" parameterType="int"> delete from smbms.user where id = #{id} </delete> </mapper>
10.編寫測試類
import com.kero.dao.UserMapper; import com.kero.pojo.User; import com.kero.utils.MyBatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class test { @Test public void test(){ SqlSession session = MyBatisUtils.getSqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); for (User l:userList) { System.out.println(l.toString()); } session.close(); } @Test public void testgetUserByID(){ SqlSession session = MyBatisUtils.getSqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); User userByID = mapper.getUserByID(1); System.out.println(userByID); session.close(); } //增刪改需要提交事務 @Test public void testaddUser(){ SqlSession session = MyBatisUtils.getSqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); int zhhgf = mapper.addUser(new User(10, "zhhgf", "1k23jbjk")); System.out.println(zhhgf); session.commit(); //提交事務 session.close(); } @Test public void testupdateUser(){ SqlSession session = MyBatisUtils.getSqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); int i = mapper.updateUser(new User(8,"asdfsdf","234sdfs")); session.commit(); //提交事務 session.close(); } @Test public void testdeleteUser(){ SqlSession session = MyBatisUtils.getSqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); int i = mapper.deleteUser(8); session.commit(); //提交事務 session.close(); } }
11.測試查詢功能 : 輸出結果與數據庫表中數據
User{id=1, name='Sugawara Ryota', pwd='8X8Jq7HVNs'}
User{id=2, name='Shawn Mills', pwd='R78IHGDSXr'}
User{id=3, name='Matsuda Hina', pwd='mUi3CVA7mc'}
User{id=4, name='Cynthia Hawkins', pwd='NO1EwWbOs9'}
User{id=5, name='Rachel Bennett', pwd='YefuPVxzb9'}
tips:
如果一切配置正常但出現java.lang.ExceptionInInitializerError
Caused by org.apache.ibatis.execeptions.PersistenceExecepyion錯誤
是因為:maven由于它的約定大于配置 我們寫的配置文件可能會出現無法被導出或者生效的問題解決方案 在pom.xml文件中添加如下代碼
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
關于“Mybatis怎么實現一個增刪改查程序”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。