一.查询
1.配置mybatis-config.xml
<?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> <!--根节点--> <!--引入外部文件--> <properties resource="jdbc.properties"></properties> <!--使用该包下的类的简单名称做别名--> <typeAliases> <package name="cn.happy.entity"></package> </typeAliases> <environments default="development"><!--环境--> <environment id="development"> <transactionManager type="JDBC"/><!--一共两种jdbc和jdbc【manage】--> <dataSource type="POOLED"><!--unpolled jndi--> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <!-- <mapper resource="cn/happy/dao/IUserInfoDao.xml"/>--> <package name="cn.happy.dao"></package> </mappers> </configuration>
2.书写实体类
public class UserInfo implements Serializable { private Integer userid; private String username; private String userpwd; private int usersex; public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } public int getUsersex() { return usersex; } public void setUsersex(int usersex) { this.usersex = usersex; } }
3.书写DAO层接口
package cn.happy.dao; import cn.happy.entity.UserInfo; import java.util.List; /** * Created by 17921 on 2017/9/10. */ public interface IUserInfoDao { //查询所有 public List<UserInfo> getList(); }
4.书写小配置
<?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="cn.happy.dao.IUserInfoDao"><!--关联的dao层文件--> <sql id="com"> userid,username,userpwd,usersex </sql> <select id="getList" resultMap="myUserMap" > select <include refid="com"></include> from userinfo </select> </mapper>
5.书写测试类
//查询所有的测试 @Test public void aa(){ String path="mybatis-config.xml"; try { InputStream is= Resources.getResourceAsStream(path); SqlSessionFactory session=new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = session.openSession(); // List<UserInfo> list = sqlSession.selectList("cn.happy.dao.IUserInfoDao.getList"); IUserInfoDao infoDao = sqlSession.getMapper(IUserInfoDao.class); List<UserInfo> list = infoDao.getList(); for (UserInfo item:list) { System.out.println(item.getUsername()+" "+item.getUsersex()+" "+item.getUserpwd()); } sqlSession.close(); } catch (IOException e) { e.printStackTrace(); } }
注:修改,添加,删除类似