Mybatis配置-简单的使用
导包
基本配置
配置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> <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/mybatis1"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments>
<mappers>
<mapper resource="cn/zys/entity/user-mapper.xml"/>
</mappers>
</configuration>
MyBatisUtils.java
package cn.zys.until; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtils { public static SqlSessionFactory getSqlSessionFactory() throws IOException{ String resource = "mybatis.config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); return sqlSessionFactory; } public static SqlSession getSqlSession() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); return sqlSessionFactory.openSession(); } }
user-mapper.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="cn.zys.entity.UserMapper"> <select id="selectUser" resultType="cn.zys.entity.User"> select name from user where id = #{id} </select> </mapper>
User.java
package cn.zys.entity; public class User { private int id; private String name; private String pwd; // public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + "]"; }
test.java
package cn.zys.test; import java.io.IOException; import org.apache.ibatis.session.SqlSession; import cn.zys.entity.User; import cn.zys.until.MyBatisUtils; public class test { public static void main(String[] args) throws IOException { SqlSession sqlsession = MyBatisUtils.getSqlSession(); User user = sqlsession.selectOne("cn.zys.entity.UserMapper.selectUser", 1); 此处命名空间加 id System.out.println(user.toString()); sqlsession.close(); } }
运行结果