1. 程式人生 > >三、基於註解入門實例

三、基於註解入門實例

tid 定義 配置 alt lse href contain source factor

1、定義操作 user 表的註解接口 UserMapper.java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.ys.annocation; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update;
import com.ys.po.User; public interface UserMapper { //根據 id 查詢 user 表數據 @Select("select * from user where id = #{id}") public User selectUserById(int id) throws Exception; //向 user 表插入一條數據 @Insert("insert into user(username,sex,birthday,address) value(#{username},#{sex},#{birthday},#{address})"
) public void insertUser(User user) throws Exception; //根據 id 修改 user 表數據 @Update("update user set username=#{username},sex=#{sex} where id=#{id}") public void updateUserById(User user) throws Exception; //根據 id 刪除 user 表數據 @Delete("delete from user where id=#{id}")
public void deleteUserById(int id) throws Exception; }

  

回到頂部

2、向 mybatis-configuration.xml 配置文件中註冊 UserMapper.java 文件

  技術分享圖片

1 2 3 <mappers> <mapper class="com.ys.annocation.UserMapper"/> </mappers>

  

回到頂部

3、創建測試類

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 package com.ys.test; import java.io.InputStream; 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; import com.ys.annocation.UserMapper; import com.ys.po.User; public class UserAnnocationTest { //定義 SqlSession SqlSession session =null; @Before public void init(){ //定義mybatis全局配置文件 String resource = "mybatis-configuration.xml"; //加載 mybatis 全局配置文件 InputStream inputStream = CRUDTest.class.getClassLoader() .getResourceAsStream(resource); //構建sqlSession的工廠 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //根據 sqlSessionFactory 產生 session session = sessionFactory.openSession(); } //註解的增刪改查方法測試 @Test public void testAnncationCRUD() throws Exception{ //根據session獲取 UserMapper接口 UserMapper userMapper = session.getMapper(UserMapper.class); //調用selectUserById()方法 User user = userMapper.selectUserById(1); System.out.println(user); //調用 insertUser() 方法 User user1 = new User(); user1.setUsername("aliks"); user1.setSex("不詳"); userMapper.insertUser(user1); //調用 updateUserById() 方法 User user2 = new User(); user2.setId(6); user2.setUsername("lbj"); userMapper.updateUserById(user2); //調用 () 方法 userMapper.deleteUserById(6); session.commit(); session.close(); } }

註意:註解配置我們不需要 userMapper.xml 文件了  

三、基於註解入門實例