实验代码
public class MyApp {
private static SqlSessionFactory sqlsessionfactory;//存储SqlSessionFactory 对象
static {
//设置配置路径,mybitis是以SqlMapConfig.xml为主路径。因为SqlMapConfig中的mapper关联了user.xml
//因为在config根目录下,所以可以直接引用而不用带config
String resource = "SqlMapConfig.xml";
//SqlMapConfig.xml读给输入流,使用mybitis的Resources类下的getResourceAsStream实现
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
//创建Mybitis的SqlSessionFactory工厂类
sqlsessionfactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static void main(String[] args) {
//通过工厂类打开数据接口
SqlSession sqlsession = sqlsessionfactory.openSession();
//设置接收对象
WeChatInfo iaWechatInfo = null;
try {
//查询数据selectOne为查询一条的方法第一个参数是user.xml中的namespace.id;第二个参数是user配置文件中的#{id}
iaWechatInfo = sqlsession.selectOne("test.findUserById", "yy0001");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
sqlsession.close();//读完要关闭sqlsession
}
System.out.println(iaWechatInfo);//打印输出
}
}
WeChatInfo.java
public class WeChatInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String weId;
private Integer iaId;
private String iaName;
//get set ....
SqlMapConfig.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配置文件, 我这里面配置的是数据库相关 -->
<properties resource="resource.properties"></properties>
<!-- 指定Mybatis使用log4j -->
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
<property name="driver" value="${jdbc.driverClass}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.userName}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 映射文件,mybatis精髓, 后面才会细讲 -->
<mappers>
<mapper resource="sqlmap/mybatis-model.xml"></mapper>
</mappers>
</configuration>
mybatis-model.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">
<!-- namespace命名空间,为了对sql语句进行隔离,方便管理 ,mapper开发dao方式,使用namespace有特殊作用 -->
<mapper namespace="test">
<!-- 在mapper.xml文件中配置很多的sql语句,执行每个sql语句时,封装为MappedStatement对象
mapper.xml以statement为单位管理sql语句
-->
<select id="findUserById" parameterType="String" resultType="com.mybatis.WeChatInfo">
SELECT * FROM TB_CRM_WECHATINFO WHERE WEID=#{weId}
</select>
</mapper>
resource.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.userName=root