mybatis第一个项目
1 public class Test { 2 public static void main(String[] args) throws IOException { 3 // 1.读取配置文件 4 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); 5 //2.创建SQLSessionFactory工厂 6 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); 7 SqlSessionFactory factory = builder.build(in); 8 //3.使用工厂生产SQLSession对象 9 SqlSession session = factory.openSession(); 10 //4.使用SQLSession创建Dao接口的代理对象 11 IUserDao userDao = session.getMapper(IUserDao.class); 12 //5.使用代理对象执行方法 13 List<User> users = userDao.findAll(); 14 for (User user : users) { 15 System.out.println(user); 16 } 17 //6.释放资源 18 session.close(); 19 in.close(); 20 } 21 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <!--mybatis的主配置文件--> 6 <configuration> 7 <!--配置环境--> 8 <environments default="mysql"> 9 <!--配置mysql的环境--> 10 <environment id="mysql"> 11 <!--配置事务类型--> 12 <transactionManager type="JDBC"></transactionManager> 13 <!--配置数据源(连接池)--> 14 <dataSource type="POOLED"> 15 <!--配置连接数据库的4个基本信息--> 16 <property name="driver" value="com.mysql.jdbc.Driver"/> 17 <property name="url" value="jdbc:mysql://localhost:3306/db1"/> 18 <property name="username" value="root"/> 19 <property name="password" value="root"/> 20 </dataSource> 21 </environment> 22 </environments> 23 <!--指定映射文件的位置 ,映射配置文件指的是每个dao独立的配置文件--> 24 <mappers> 25 <mapper resource="com/itheima/dao/IUserDao.xml"/> 26 </mappers> 27 </configuration>
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="com.itheima.dao.IUserDao"> 6 <!--配置查询所有--> 7 <select id="findAll" resultType="com.itheima.domain.User"> 8 select * from user 9 </select> 10 </mapper>
package com.itheima.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private Integer id; private String username; private Date birthday; private String sex; private String 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; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } }
package com.itheima.dao; import com.itheima.domain.User; import java.util.List; public interface IUserDao { List<User> findAll(); }