mybatis 接口形式访问

一.导入资源


	
		org.mybatis
		mybatis
		3.3.0
	

	
		mysql
		mysql-connector-java
		5.1.20
	
	
		junit
		junit
		4.12
	
二.创建数据库表

USE `mybatis`;
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `user` */
insert  into `user`(`id`,`name`) values (1,'update');
三.创建User类

public class User {

	private int id;
	private String name;

	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;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}

}
四.创建UserDao接口以及UserMapping.xml

public interface UserDao {
	public User selectUserByID(int id);
}




	
五.创建配置文件mybatis-config.xml以及数据库配置文件config.properties




	
	
	
		
	
	
		
			
			
				
				
				
				
			
		
	
	
		
	



driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mybatis
username=root
password=root
六.编写单元测试
public class UserDaoTest {

	SqlSession session = null;

	@Before
	public void setUp() throws Exception {

		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		session = sqlSessionFactory.openSession();

	}

	@After
	public void tearDown() throws Exception {
		session.commit();
		session.close();
	}

	@Test
	public void testSelectUserById() {
		UserDao userDao = (UserDao) session.getMapper(UserDao.class);
		User user = userDao.selectUserByID(1);
		assertEquals(user.getName(), "update");
	}

}

源码链接:https://github.com/wangjianyangchn/myBatis/tree/master/ByInterface


参考文档:http://www.mybatis.org/mybatis-3/zh/index.html

你可能感兴趣的:(mybatis)