Mybatis通过注解方式访问数据库(intellij)
一、连接的方式
-
创建Maven工程并导入坐标
-
创建实体类和dao接口文件
-
创建Mybatis的主配置文件 SqlMapConfig.xml
二、具体连接方式
1. 首先在Resources文件夹下面建立 SqlMapConfig.xml 文件
2. 建立相应的实体类和对应的接口
(1)/src/main/java/com/xxx/dao
IUserDao.javapublic interface IUserDao { // 用户持久层接口 @Select("select * from user") // 注解方式进行相应的数据处理操作 List findAll();}
(2) /src/main/java/com/xxx/domain 包 建立相应接口文件
User.java//public class User { private Integer id; private String username; private Date birthday; private String sex; private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; }}
public static void main(String[] args)throws Exception {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
IUserDao userDao = session.getMapper(IUserDao.class);
//5.使用代理对象执行方法
List users = userDao.findAll();
for(User user : users) {
System.out.println(user);
}
//6.释放资源
session.close(); //
in.close();
}
网友评论