实现一个简单的查询程序
1 新建web项目
2 添加jar包
3 创建数据库和用户表
#创建数据库
Create TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`userAge` int(11) DEFAULT NULL,
`userAddress` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
#添加记录
Insert INTO `user` VALUES ('1', 'retacn', '30', 'shangdong zibo');
开始项目代码:
使用xml构建sqlSessionFactory
1 新建两个源码文件src test_src
2 在src/cn/yue/mybatis/models目录下新建User和User.xml
示例代码如下:
user.java
public class User {
/* id */
private int id;
/* 用户名 */
private String userName;
/* 年龄 */
private String userAge;
/* 地址 */
private String userAddress;
//getter/setter
}
user.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">
<!-- 按照用户id进行查询 -->
<mapper namespace="cn.yue.mybatis.models.UserMapper">
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
3 src目录下添加配置文件Configuration.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="org/mybatis/example/config.properties">
<property name="username" value="root" /> <property name="password" value="yue4512138"
/> </properties> -->
<!-- 可以修改mybatis运行时的行为 -->
<settings>
<!-- 全局映射器是否缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 全局延迟加载 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 是否允许多个结果集从一个语句中返回 -->
<setting name="multipleResultSetsEnabled" value="true" />
<!-- 使用列标签代替列名 -->
<setting name="useColumnLabel" value="true" />
<!-- 允许jdbc支持生成的键 -->
<setting name="useGeneratedKeys" value="false" />
<!-- -->
<setting name="enhancementEnabled" value="false" />
<!-- 配置默认的执行器 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 设置超时时间 -->
<setting name="defaultStatementTimeout" value="25000" />
</settings>
<!-- 类型命名 类似于起别名 -->
<typeAliases>
<typeAlias alias="User" type="cn.yue.mybatis.model.User" />
</typeAliases>
<!-- 类型处理器,处理不支持类型 <typeHandlers> <typeHandler javaType="String" jdbcType="VARCHAR"
handler="org.mybatis.example.ExampleTypeHandler" /> </typeHandlers> -->
<!-- 环境,可以配置多种环境(多数据库) -->
<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://127.0.0.1:3306/mybatis_demo" />
<property name="username" value="root" />
<property name="password" value="yue4512138" />
</dataSource>
</environment>
</environments>
<!--插件 用来建立sectionFactory -->
<plugins>
<plugin interceptor="cn.yue.mybatis.utils.PagePlugin">
<property name="dialect" value="mysql" />
<property name="pageSqlId" value=".*ListPage.*" />
</plugin>
</plugins>
<!-- 映射类的配置文件交由sprig处理 <mappers> <mapper resource="cn/yue/mybatis/mapper/User.xml"
/> </mappers> -->
</configuration>
4 测试程序
test_src/cn.yue.test.Test,文件内容如下:
public class Test {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
// 加载配置文件
static {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
User user = session.selectOne("cn.yue.mybatis.models.UserMapper.selectUserByID", 1);
System.out.println("userName: " + user.getUserName());
System.out.println("userAddress: " + user.getUserAddress());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
}
以接口方式编程
1 在srt/cn.yue.mabatis.inter下添加IUserOperation
示例代码如下:
public interface IUserOperation {
/* 按用户id查询用户 方法与xml中对应*/
public User selectUserByID(int id);
}
2 修改User.xml配置文件
<!-- 按照用户id进行查询 -->
<mapper namespace="cn.yue.mybatis.inter.IUserOperation">
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
3 测试
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
// 方式一:
// User user =
// session.selectOne("cn.yue.mybatis.models.IUserOperation.selectUserByID",
// 1);
// 方式二:
IUserOperation userOperation = session.getMapper(IUserOperation.class);
User user = userOperation.selectUserByID(1);
System.out.println("userName: " + user.getUserName());
System.out.println("userAddress: " + user.getUserAddress());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
参考:http://blog.csdn.net/techbirds_bao/article/details/9233599/