MyBatis经典入门实例
2015-12-27 11:34
351 查看
MyBatis经典入门实例
分类: Java技术2010-08-02
14:51 35751人阅读 评论(27) 收藏 举报
string持久层框架encodingsql数据库insert
周末学习了MyBatis开源框架,MyBatis是由原来的iBatis改名而来,目前已近发布了3.0.1版本。可以在官方网站http://www.mybatis.org下载。
MyBatis作为持久层框架,其主要思想是将程序中的大量sql语句剥离出来,配置在配置文件中,实现sql的灵活配置。这样做的好处是将sql与程序代码分离,可以在不修改程序代码的情况下,直接在配置文件中修改sql。下面给个简单的入门例子。
下面的例子实现从数据库中查询商品表(Goods)中id为1的商品,并打印出商品名称。
数据库建表脚本如下:
DROP TABLE GOODS;
CREATE TABLE GOODS(
ID INT PRIMARY KEY,
CATE_ID INT,
NAME VARCHAR(50),
PRICEDECIMAL(16,2),
DESCRIPTIONVARCHAR(100),
ORDER_NO INT,
UPDATE_TIMETIMESTAMP
);
数据库初始化脚本:
INSERTINTOGOODS(ID,CATE_ID,NAME,PRICE,DESCRIPTION,ORDER_NO,UPDATE_TIME)
VALUES (1,1,'诺基亚N85',3010,'内置RealPlayer播放器',1,CURRENT_TIMESTAMP);
INSERTINTOGOODS(ID,CATE_ID,NAME,PRICE,DESCRIPTION,ORDER_NO,UPDATE_TIME)
VALUES (2,1,'金立
A30',2000,'标准锂电池两块',2,CURRENT_TIMESTAMP);
一、configuration.xml配置文件
首先在工程中导入mybatis-3.0.1.jar包。然后编写configuration.xml配置文件。
xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEconfiguration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAliasalias="Goods"
type="com.oryx.mybatis.Goods"/>
typeAliases>
<environmentsdefault="development">
<environmentid="development">
<transactionManagertype="JDBC"/>
<dataSourcetype="POOLED">
<propertyname="driver"
value="com.mysql.jdbc.Driver"/>
<propertyname="url"
value="jdbc:mysql://localhost:3306/test"/>
<propertyname="username"
value="root"/>
<propertyname="password"
value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapperresource="com/oryx/mybatis/GoodsMapper.xml"/>
mappers>
configuration>
二、Mapper.xml配置文件
接着编写GoodsMapper.xml配置文件。Mapper配置文件主要是实现POJO类和sql之间的映射。
xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="com.oryx.mybatis.GoodsMapper">
<selectid="selectGood"
parameterType="int"
resultType="Goods">
select * from Goodswhere id = #{id}
select>
mapper>
其中#{id}是需要传入的参数,parameterType是参数的类型,resultType是查询返回的结果类。这地方的Goods是一个别名,可以在configuration.xml文件中找到它对应的具体类。
由此可知查询结果集将保存在com.oryx.mybatis.Goods中返回。
三、Goods类
在工程中新建com.oryx.mybatis.Goods.java类。
package com.oryx.mybatis;
import java.sql.Timestamp;
publicclass Goods {
private String id;
private String cateId;
private String name;
privatedouble price;
private String description;
privateint orderNo;
private Timestamp updateTime;
/**
* @return the goodsid
*/
public String getId() {
return id;
}
/**
* @param goodsid thegoodsid to set
*/
publicvoid setId(String id) {
this.id = id;
}
/**
* @return the cateId
*/
public String getCateId() {
return cateId;
}
/**
* @param cateId thecateId to set
*/
publicvoid setCateId(String cateId) {
this.cateId = cateId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name thename to set
*/
publicvoid setName(String name) {
this.name = name;
}
/**
* @return the price
*/
publicdouble getPrice() {
return price;
}
/**
* @param price theprice to set
*/
publicvoid setPrice(doubleprice) {
this.price = price;
}
/**
* @return thedescription
*/
public String getDescription() {
return description;
}
/**
* @param descriptionthe description to set
*/
publicvoid setDescription(String description) {
this.description = description;
}
/**
* @return the orderNo
*/
publicint getOrderNo() {
return orderNo;
}
/**
* @param orderNo theorderNo to set
*/
publicvoid setOrderNo(intorderNo) {
this.orderNo = orderNo;
}
/**
* @return theupdateTime
*/
public Timestamp getUpdateTime() {
return updateTime;
}
/**
* @param updateTimethe updateTime to set
*/
publicvoid setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
}
四、测试用例
packagecom.oryx.mybatis;
importjava.io.IOException;
importjava.io.Reader;
importjava.sql.SQLException;
importorg.apache.ibatis.io.Resources;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.apache.ibatis.session.SqlSessionFactoryBuilder;
publicclass TestMyBatis {
publicstaticvoid main(String[] args) throws SQLException,IOException{
String resource ="com/oryx/mybatis/configuration.xml";
Reader reader =Resources.getResourceAsReader(resource);
SqlSessionFactorysessionFactory =
new SqlSessionFactoryBuilder().build(reader);
SqlSession session= sessionFactory.openSession();
try{
Goods goods =(Goods)session.selectOne("com.oryx.mybatis.GoodsMapper.selectGoods",1);
System.out.println("good name:"+goods.getName());
}finally{
session.close();
}
}
}
实例源代码下载。
版权声明:本文为博主原创文章,未经博主允许不得转载。
· 上一篇混乱的日子
· 下一篇GCCollector.jar无法运行的解决方法
主题推荐
数据库color实例mybatis持久层框架开源框架
分类: Java技术2010-08-02
14:51 35751人阅读 评论(27) 收藏 举报
string持久层框架encodingsql数据库insert
周末学习了MyBatis开源框架,MyBatis是由原来的iBatis改名而来,目前已近发布了3.0.1版本。可以在官方网站http://www.mybatis.org下载。
MyBatis作为持久层框架,其主要思想是将程序中的大量sql语句剥离出来,配置在配置文件中,实现sql的灵活配置。这样做的好处是将sql与程序代码分离,可以在不修改程序代码的情况下,直接在配置文件中修改sql。下面给个简单的入门例子。
下面的例子实现从数据库中查询商品表(Goods)中id为1的商品,并打印出商品名称。
数据库建表脚本如下:
DROP TABLE GOODS;
CREATE TABLE GOODS(
ID INT PRIMARY KEY,
CATE_ID INT,
NAME VARCHAR(50),
PRICEDECIMAL(16,2),
DESCRIPTIONVARCHAR(100),
ORDER_NO INT,
UPDATE_TIMETIMESTAMP
);
数据库初始化脚本:
INSERTINTOGOODS(ID,CATE_ID,NAME,PRICE,DESCRIPTION,ORDER_NO,UPDATE_TIME)
VALUES (1,1,'诺基亚N85',3010,'内置RealPlayer播放器',1,CURRENT_TIMESTAMP);
INSERTINTOGOODS(ID,CATE_ID,NAME,PRICE,DESCRIPTION,ORDER_NO,UPDATE_TIME)
VALUES (2,1,'金立
A30',2000,'标准锂电池两块',2,CURRENT_TIMESTAMP);
一、configuration.xml配置文件
首先在工程中导入mybatis-3.0.1.jar包。然后编写configuration.xml配置文件。
xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEconfiguration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAliasalias="Goods"
type="com.oryx.mybatis.Goods"/>
typeAliases>
<environmentsdefault="development">
<environmentid="development">
<transactionManagertype="JDBC"/>
<dataSourcetype="POOLED">
<propertyname="driver"
value="com.mysql.jdbc.Driver"/>
<propertyname="url"
value="jdbc:mysql://localhost:3306/test"/>
<propertyname="username"
value="root"/>
<propertyname="password"
value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapperresource="com/oryx/mybatis/GoodsMapper.xml"/>
mappers>
configuration>
二、Mapper.xml配置文件
接着编写GoodsMapper.xml配置文件。Mapper配置文件主要是实现POJO类和sql之间的映射。
xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="com.oryx.mybatis.GoodsMapper">
<selectid="selectGood"
parameterType="int"
resultType="Goods">
select * from Goodswhere id = #{id}
select>
mapper>
其中#{id}是需要传入的参数,parameterType是参数的类型,resultType是查询返回的结果类。这地方的Goods是一个别名,可以在configuration.xml文件中找到它对应的具体类。
由此可知查询结果集将保存在com.oryx.mybatis.Goods中返回。
三、Goods类
在工程中新建com.oryx.mybatis.Goods.java类。
package com.oryx.mybatis;
import java.sql.Timestamp;
publicclass Goods {
private String id;
private String cateId;
private String name;
privatedouble price;
private String description;
privateint orderNo;
private Timestamp updateTime;
/**
* @return the goodsid
*/
public String getId() {
return id;
}
/**
* @param goodsid thegoodsid to set
*/
publicvoid setId(String id) {
this.id = id;
}
/**
* @return the cateId
*/
public String getCateId() {
return cateId;
}
/**
* @param cateId thecateId to set
*/
publicvoid setCateId(String cateId) {
this.cateId = cateId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name thename to set
*/
publicvoid setName(String name) {
this.name = name;
}
/**
* @return the price
*/
publicdouble getPrice() {
return price;
}
/**
* @param price theprice to set
*/
publicvoid setPrice(doubleprice) {
this.price = price;
}
/**
* @return thedescription
*/
public String getDescription() {
return description;
}
/**
* @param descriptionthe description to set
*/
publicvoid setDescription(String description) {
this.description = description;
}
/**
* @return the orderNo
*/
publicint getOrderNo() {
return orderNo;
}
/**
* @param orderNo theorderNo to set
*/
publicvoid setOrderNo(intorderNo) {
this.orderNo = orderNo;
}
/**
* @return theupdateTime
*/
public Timestamp getUpdateTime() {
return updateTime;
}
/**
* @param updateTimethe updateTime to set
*/
publicvoid setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
}
四、测试用例
packagecom.oryx.mybatis;
importjava.io.IOException;
importjava.io.Reader;
importjava.sql.SQLException;
importorg.apache.ibatis.io.Resources;
importorg.apache.ibatis.session.SqlSession;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.apache.ibatis.session.SqlSessionFactoryBuilder;
publicclass TestMyBatis {
publicstaticvoid main(String[] args) throws SQLException,IOException{
String resource ="com/oryx/mybatis/configuration.xml";
Reader reader =Resources.getResourceAsReader(resource);
SqlSessionFactorysessionFactory =
new SqlSessionFactoryBuilder().build(reader);
SqlSession session= sessionFactory.openSession();
try{
Goods goods =(Goods)session.selectOne("com.oryx.mybatis.GoodsMapper.selectGoods",1);
System.out.println("good name:"+goods.getName());
}finally{
session.close();
}
}
}
实例源代码下载。
版权声明:本文为博主原创文章,未经博主允许不得转载。
· 上一篇混乱的日子
· 下一篇GCCollector.jar无法运行的解决方法
主题推荐
数据库color实例mybatis持久层框架开源框架
相关文章推荐
- Java中有关Null的9件事
- memcached之java客户端:spymemcached与spring整合
- 将函数名(地址)作为参数传递
- 自然语言处理
- CentOS 7部署OpenStack(1)-―准备基础环境
- List#toArray小技巧
- Android 图形 II-OpenGL ES
- 华为oj:判断两个IP是否属于同一个子网
- 通知栏通知:Notification的实现
- atitit.团队建设--要不要招技术储备人才的问题
- 课程总结报告
- 关于comparable与comparator的用法(即自定义集合框架用法 )
- special filter for iptables/netfilter tcpdump/tshark/wireshark
- 如何用MinGW 命令行编译链接c/c++
- ABP理论学习之数据过滤器
- ServerSAN解析(一):vVNX专业存储设备虚拟化
- ServerSAN解析(一):vVNX专业存储设备虚拟化
- 哈夫曼树的实现
- java中String类详解(收集)
- LeetCode-16-3Sum Closest(证明/KSum)-Medium