第一个配置文件
<?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">
<!-- 通过这个配置文件完成mybatis与数据库的连接 -->
<configuration>
<environments default="dev">
<!--环境配置 -->
<environment id="dev">
<!--使用jdbc事务 -->
<transactionManager type="JDBC"></transactionManager>
<!--数据源:mybatis自带连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="/com/zn/mapper/UserMapper.xml"/>
</mappers>
</configuration>
第二个配置文件
<?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.zn.mapper.UserMapper">
<select id="count" resultType="String">
select * from smbms_user where name=?
</select>
</mapper>
测试
public class Test {
public static void main(String[] args) throws IOException {
//1.读配置文件
String resource="mybatis-config.xml";
InputStream is=Resources.getResourceAsStream(resource);
List<User> userList=new ArrayList<User>();
//2.获取连接SqlSession-->Connection
SqlSessionFactory sqlFacotry=new SqlSessionFactoryBuilder().build(is);//sqlsession工厂
SqlSession sqlSession=sqlFacotry.openSession();//获得连接
System.out.println(sqlSession);
//3.查询用户个数select count(1) from smbms_user;
//命名空间。ID值
Object obj=sqlSession.selectOne("com.zn.mapper.UserMapper.count");//根据路径找到那边的sql语句
System.out.println(obj);
for(User user:userList){
System.out.println("用户名"+user.getUserName()+"编码"+user.getUserCode());
}
sqlSession.close();//关闭流
}
查询用户所有信息 返回类型用户实体类