需要jar包:mybatis-3.x.x.jar 、假设需要和spring综合,此外,我们需要增加相关的包
1:看到项目文件夹 不要在意红色
2:依照步骤:
1:增加jar包
2:创建数据源(configuration.xml)创建数据库(此处省略)
3:创建实体类USER
package com.forum.po;/** * 用户类 * * @author db2admin * */public class User extends Entity { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User() { }}4:创建dao接口、能够说是Mapper接口:UserMapper
package com.forum.dao;import com.forum.po.User;public interface UserMapper { public User findById(String Id);}5:创建dao的实现,不同于hibernarte的此处的实现为一个xml文件,也就是userMapper.xml
6:測试类。MyBatisTest
package com.forum.test;import java.io.IOException;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 com.forum.dao.UserMapper;import com.forum.po.User;/** * myBatis数据库连接測试 * * @author db2admin * */public class MyBatisTest { /** * 获得MyBatis SqlSessionFactory * SqlSessionFactory负责创建SqlSession。一旦创建成功,就能够用SqlSession实例来运行映射语句,commit。rollback,close等方法。 * @return */ private static SqlSessionFactory getSessionFactory() { SqlSessionFactory sessionFactory = null; String resource = "configuration.xml"; try { sessionFactory = new SqlSessionFactoryBuilder().build(Resources .getResourceAsReader(resource)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sessionFactory; } public static void main(String[] args) { SqlSession sqlSession = getSessionFactory().openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findById("1"); System.out.println(user.getName()); }}