查詢單條信息的在 http://www.cnblogs.com/tk55/p/6659285.html 已經有了 XML 修改UserMapper.xml 修改Test.java 結果 註解 UserMapper.java mybatis-config.xml Test.java 結果 ...
查詢單條信息的在
http://www.cnblogs.com/tk55/p/6659285.html 已經有了
XML
修改UserMapper.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.ij34.mybatis.UserMapper"> <resultMap type="com.ij34.model.User" id="resultListUser"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> </resultMap> <select id="selectUser" resultMap="resultListUser" > select * from users; </select> </mapper>
修改Test.java
package com.ij34.bean; import java.io.IOException; import java.io.InputStream; import java.util.List; 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.ij34.model.User; public class Test { public static void main(String[] args) throws IOException { String resource ="com/ij34/mybatis/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session=sqlSessionFactory.openSession(); try { List<User> users=session.selectList("com.ij34.mybatis.UserMapper.selectUser"); // UserMapper mapper=session.getMapper(UserMapper.class); // User user=mapper.selectUser(1);; for(User user:users){ System.out.println(user); } } finally { // TODO: handle finally clause session.close(); } } }
結果
註解
UserMapper.java
package com.ij34.model; import java.util.List; import org.apache.ibatis.annotations.Select; public interface UserMapper { @Select("select * from users") public List<User> selectUser(); }
mybatis-config.xml
<mappers>
<mapper class="com.ij34.model.UserMapper"/>
</mappers>
Test.java
package com.ij34.bean; import java.io.IOException; import java.io.InputStream; import java.util.List; 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.ij34.model.User; import com.ij34.model.UserMapper; public class Test { public static void main(String[] args) throws IOException { String resource ="com/ij34/mybatis/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session=sqlSessionFactory.openSession(); try { // List<User> users=session.selectList("com.ij34.mybatis.UserMapper.selectUser"); UserMapper mapper=session.getMapper(UserMapper.class); List<User> users=mapper.selectUser(); for(User user:users){ System.out.println(user); } } finally { // TODO: handle finally clause session.close(); } } }
結果