我的第一个Mybatis程序——Maven项目
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis/useSSL=true&userUnicode=code&characterEncoding=UTF-8"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> </configuration> </>
1.2 编写工具类
//编写工具类 public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { String resource="mybatis.config.xml"; try { //使用Mybatis第一步获取配置文件 InputStream inputStream= Resources.getResourceAsStream(resource); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession gerSqlSession(){ return sqlSessionFactory.openSession(); } }
然后需要创建Mapper(Dao)层接口
public interface UserMapper{ List<User> getAllUsers(); }
当然还需要创建实体类
public class User{ int id; String name; String pwd; // 各种setter getter方法 有参构造无参构造 }
我们之前使用mvc分层需要创建Dao层的实现类,但是在Mybatis中实现类改为xml配置文件代替
//将原来的实现类 通过xml文件实现 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.MouseFour.Dao"> <select id="getUserList"> select * from mybatis.user </select> </mapper>
重点 :因为mapper文件实在java目录下,可能遇到不会导出的情况,所以需要在pom添加以下配置收手动导出
<build> <resources> <resource> <directory>src/main/resource</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
在Mybatis注册文件中注册Mapper路径
...... <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> ......
测试
public class UserDaoTest { @Test public void test(){ //第一步获取sqlsession对象 SqlSession sqlSession=MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(new Gson().toJson(user)); } sqlSession.close(); } }