使用mybatis以介面開發方式程式設計
阿新 • • 發佈:2019-01-27
一、先在\src\main\java下建立一個包,包名為com.hgc.inter,然後在該包下建立UserInterface.java,該檔案程式碼如下
package com.hgc.inter;
import com.hgc.pojo.User;
import org.apache.ibatis.annotations.Select;
/**
* Created by 47500 on 2017/9/7.
*/
public interface UserInterface {
@Select("SELECT * FROM user WHERE id=#{id}")
public User selectUserByID(int id);
}
二、在src\main下建立test資料夾,然後在該資料夾下建立UserTest.java,程式碼如下
import com.hgc.inter.UserInterface;
import com.hgc.pojo.User;
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 java.io.Reader;
/**
* Created by 47500 on 2017/9/7.
*/
public class UserTest {
/**
* 根據介面及註釋獲取資料
*/
@Test
public void findByIdByInter() throws Exception{
String resource ="mybatis-config.xml";
Reader reader = null;
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
//註冊該介面
sqlSessionFactory.getConfiguration().addMapper(UserInterface.class);
//
SqlSession session = sqlSessionFactory.openSession();
UserInterface userInterface = session.getMapper(UserInterface.class);
User user = userInterface.selectUserByID(1);
System.out.println(user.getName());
}
}