MyBatis经典入门实例

周末学习了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),

PRICE DECIMAL(16,2),

DESCRIPTION VARCHAR(100),

ORDER_NO INT,

UPDATE_TIME TIMESTAMP

);

数据库初始化脚本:

INSERT INTO GOODS(ID,CATE_ID,NAME,PRICE,DESCRIPTION,ORDER_NO,UPDATE_TIME) VALUES (1,1,'诺基亚N85',3010,'内置RealPlayer播放器',1,CURRENT_TIMESTAMP);

INSERT INTO GOODS(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配置文件。

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>

<typeAliases>

<typeAlias alias="Goods" type="com.oryx.mybatis.Goods"/>

typeAliases>

<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/test"/>

<property name="username" value="root"/>

<property name="password" value="root"/>

dataSource>

environment>

environments>

<mappers>

<mapper resource="com/oryx/mybatis/GoodsMapper.xml"/>

mappers> configuration>

 

二、Mapper.xml配置文件

接着编写GoodsMapper.xml配置文件。Mapper配置文件主要是实现POJO类和sql之间的映射。

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.oryx.mybatis.GoodsMapper">

<select id="selectGoods" parameterType="int" resultType="Goods">

select * from Goods where 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;

public class Goods {

private String id;

private String cateId;

private String name;

private double price;

private String description;

private int orderNo;

private Timestamp updateTime;

/**

* @return the goodsid

*/

public String getId() {

return id;

}

/**

* @param goodsid the goodsid to set

*/

public void setId(String id) {

this.id = id;

}

/**

* @return the cateId

*/

public String getCateId() {

return cateId;

}

/**

* @param cateId the cateId to set

*/

public void setCateId(String cateId) {

this.cateId = cateId;

}

/**

* @return the name

*/

public String getName() {

return name;

}

/**

* @param name the name to set

*/

public void setName(String name) {

this.name = name;

}

/**

* @return the price

*/

public double getPrice() {

return price;

}

/**

* @param price the price to set

*/

public void setPrice(double price) {

this.price = price;

}

/**

* @return the description

*/

public String getDescription() {

return description;

}

/**

* @param description the description to set

*/

public void setDescription(String description) {

this.description = description;

}

/**

* @return the orderNo

*/

public int getOrderNo() {

return orderNo;

}

/**

* @param orderNo the orderNo to set

*/

public void setOrderNo(int orderNo) {

this.orderNo = orderNo;

}

/**

* @return the updateTime

*/

public Timestamp getUpdateTime() {

return updateTime;

}

/**

* @param updateTime the updateTime to set

*/

public void setUpdateTime(Timestamp updateTime) {

this.updateTime = updateTime;

}

}

 

四、测试用例

package com.oryx.mybatis;

import java.io.IOException;

import java.io.Reader;

import java.sql.SQLException;

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 TestMyBatis {

public static void main(String[] args) throws SQLException, IOException{

String resource = "com/oryx/mybatis/configuration.xml";

Reader reader = Resources.getResourceAsReader(resource);

SqlSessionFactory sessionFactory = 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();

}

}

}
实例源代码下载
  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 27
    评论
MyBatis是一种持久化框架,可以帮助开发人员管理数据库访问,提供了一种简化SQL语句编写和数据访问的方法。在这里,我将为您提供一个快速入门指南,以帮助您开始使用MyBatis。 1. 环境设置 在开始使用MyBatis之前,您需要在计算机上安装Java和MyBatis。您可以在MyBatis官网上下载MyBatis,并按照步骤进行安装。 2. 创建数据库表 在使用MyBatis之前,您需要创建一个数据库表来存储数据。在这里,我将创建一个名为“用户”的表,其中包含id、姓名和年龄字段。 CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 3. 创建POJO类 在使用MyBatis之前,您需要创建一个POJO类来表示数据库表中的数据。在这里,我将创建一个名为“User”的类,并在其中添加id、name和age字段的getter和setter方法。 public class User { private int id; private String name; private int age; // getter and setter methods } 4. 创建Mapper接口和XML文件 在MyBatis中,Mapper是一个接口,它定义了与数据库进行交互的方法。在这里,我将创建一个名为“UserMapper”的接口,并在其中添加一个名为“selectUserById”的方法,该方法将返回具有指定ID的用户。 public interface UserMapper { User selectUserById(int id); } 接下来,我们需要创建一个名为“UserMapper.xml”的XML文件,该文件将包含与Mapper接口中方法对应的SQL语句。 <?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.example.mapper.UserMapper"> <select id="selectUserById" parameterType="int" resultType="com.example.pojo.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper> 5. 配置MyBatis 现在,我们需要将MyBatis配置为使用我们创建的Mapper接口和XML文件。我们需要创建一个名为“mybatis-config.xml”的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/mybatis"/> <property name="username" value="root"/> <property name="password" value="password"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/example/mapper/UserMapper.xml"/> </mappers> </configuration> 在这里,我们为MyBatis配置了一个数据源,该数据源将连接到MySQL数据库,并指定了Mapper文件的位置。 6. 测试MyBatis 现在,我们已经准备好使用MyBatis了。我们可以在Java代码中使用MyBatis来获取具有指定ID的用户。在这里,我将提供一个简单的示例: public class Main { public static void main(String[] args) { SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession session = sessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); User user = userMapper.selectUserById(1); System.out.println(user.getName()); } } 在这里,我们使用SqlSessionFactoryBuilder类从mybatis-config.xml文件中创建SqlSessionFactory对象。然后,我们打开一个SqlSession对象并获取UserMapper接口的实例。最后,我们调用selectUserById方法并打印用户的名称。 这就是MyBatis的快速入门指南。希望这能帮助您开始使用MyBatis,并为您提供一个更好的方法来管理数据库访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值