mybatis入门例子

mybatis是由ibatis发展而来的,是一个很好用的javaee持久化框架,很容易学,下面是一个增删改查的小例子

简单的pojo类


package com.own.entity;

public class Goods {

public int getGoodsId() {
return goodsId;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
private int goodsId;
private String goodName;
private double price;

}





数据库sql语句

/*
Navicat MySQL Data Transfer

Source Server : mysql
Source Server Version : 50165
Source Host : localhost:3306
Source Database : testdb

Target Server Type : MYSQL
Target Server Version : 50165
File Encoding : 65001

Date: 2012-09-11 12:46:12
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `goods`
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`goodsId` int(11) unsigned NOT NULL AUTO_INCREMENT,
`price` double(10,2) NOT NULL,
`goodName` varchar(20) NOT NULL,
PRIMARY KEY (`goodsId`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES ('1', '1.54', '冰激凌');
INSERT INTO `goods` VALUES ('2', '3.60', '面包');
INSERT INTO `goods` VALUES ('7', '5200.00', 'thinkpad笔记本');
INSERT INTO `goods` VALUES ('8', '5200.00', 'thinkpad笔记本');



和hibernate一样,它也需要一个全局配置文件,用于指定程序正常运行所需的设置和参数信息。它也需要一个数据库表和javabean的映射信息文件,称之为映射文件

全局配置文件 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>

<!--为java类指定别名,可以再xml文件中用别名取代java类的全限定名 -->
<typeAliases>
<typeAlias alias="Goods" type="com.own.entity.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://127.0.0.1:3306/testdb"/>
<property name="username" value="root"/>
<property name="password" value="zyp"/>
</dataSource>
</environment>
</environments>

<!-- 引入sql映射文件 -->
<mappers>
<mapper resource="com/own/entity/goodsMapper.xml"/>
</mappers>


</configuration>


sql映射文件

goodsMapper.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="com.own.GoodsMapper">

<!-- java 对象与数据库字段对应,如果数据库字段与java对象属性名称一样,可以不写 -->
<resultMap type="Goods" id="goodsId">
<result column="goodsId" property="goodsId" javaType="int" />
<result column="goodName" property="goodName" javaType="string" />
<result column="price" property="price" javaType="float" />
</resultMap>

<!-- 查询语句,parameterType为sql语句参数的类型,resultType 为执行这个 语句的返回类型-->
<select id="selectGoods" parameterType="int" resultType="Goods">
select goodsId,goodName from goods where goodsId = #{goodsId}
</select>

<insert id="insertGoods" parameterType="Goods" useGeneratedKeys="true" keyProperty="goodsId" keyColumn="goodsId" >
insert into goods(goodName,price) values(#{goodName},#{price})
</insert>

<delete id="deleteGoods" parameterType="int" >
delete from goods where goodsId=#{goodsId}
</delete>
<!-- 传递多个参数,使用javaBean 这里要注意参数的名字(也就是#{}里面的参数)一定要和javaBean属性名字一样,否则会抛出异常(mybatis要调用getxxx给参数赋值) -->
<update id="updateGoods" parameterType="Goods" >
update goods set price=#{price} where goodsId=#{goodsId}
</update>
<!-- 使用map传递多个参数 参数名称为的key -->
<update id="updateGoodsByMapParam" parameterType="map" >
update goods set price=#{price} where goodsId=#{id};
</update>
</mapper>



mybatis为我们提供了SqlSessionFactory接口,用来创建SqlSession,一个用来获得
SqlSession的类

package com.own.util;

import java.io.IOException;
import java.io.Reader;

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

private static SqlSessionFactory sqlSessionFactory;

static{

String resourceLocation = "mybatis-config.xml";

Reader reader = null;
try {
//Resources mybatis 用来加载各种配置文件,这里我们从类路径加载
reader = Resources.getResourceAsReader(resourceLocation);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}




}

public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}



}



dao类


package com.own.dao;

import java.util.Map;

import com.own.entity.Goods;

public interface GoodsDao {
/**
* 根据id得到商品
* @param id
* @return
*/
Goods getGoodsById(int id);
/**
* 存放商品
* @param good
* @return
*/
int saveGoods(Goods good);
/**
* 删除id删除商品
* @param id
* @return
*/
int deleteGoodsById(int id);
/*
* 更新一个商品
*/
int updateGoodsById(Goods good);

/*
* 根据map参数更新对象
*/
int updateGoodsById(Map<String,Object> map);

}




dao实现类



package com.own.dao.impl;

import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import com.own.dao.GoodsDao;
import com.own.entity.Goods;
import com.own.util.MybatisHelper;

public class GoodsDaoImpl implements GoodsDao {


@Override
public Goods getGoodsById(int id) {
// TODO Auto-generated method stub

SqlSession sqlSession = MybatisHelper.getSqlSession();
Goods goods = null;
try {
goods = sqlSession.selectOne("com.own.GoodsMapper.selectGoods",id);
sqlSession.commit();
}finally {
sqlSession.close();
}

return goods;

}

@Override
public int saveGoods(Goods good) {
// TODO Auto-generated method stub
SqlSession sqlSession = MybatisHelper.getSqlSession();
int result = -1;

try {
result = sqlSession.insert("com.own.GoodsMapper.insertGoods",good);
sqlSession.commit();
}finally {

sqlSession.close();

}
return result;

}

@Override
public int deleteGoodsById(int id) {
// TODO Auto-generated method stub
SqlSession sqlSession = MybatisHelper.getSqlSession();
int result = -1;

try {
result = sqlSession.delete("com.own.GoodsMapper.deleteGoods",id);
sqlSession.commit();
}finally {

sqlSession.close();

}
return result;
}

@Override
public int updateGoodsById(Goods goods) {
// TODO Auto-generated method stub

SqlSession sqlSession = MybatisHelper.getSqlSession();
int result = -1;

try {
result = sqlSession.update("com.own.GoodsMapper.updateGoods",goods);
sqlSession.commit();
}finally {
sqlSession.close();

}
return result;


}

@Override
public int updateGoodsById(Map<String, Object> map) {
// TODO Auto-generated method stub

SqlSession sqlSession = MybatisHelper.getSqlSession();
int result = -1;

try {
result = sqlSession.update("com.own.GoodsMapper.updateGoodsByMapParam",map);
sqlSession.commit();
}finally {
sqlSession.close();

}
return result;
}


}




测试类



package com.own.dao.impl;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import com.own.dao.GoodsDao;
import com.own.entity.Goods;

public class GoodsDaoImplTest {

private GoodsDao goodsDao = null;

@Before
public void setUp(){
goodsDao = new GoodsDaoImpl();
}


@Test
public void testGetGoodsById() {
Goods goods = goodsDao.getGoodsById(2);
System.out.print(goods.getPrice());
}

@Test
public void testInsertGoods(){
Goods goods = new Goods();
goods.setGoodName("thinkpad笔记本");
goods.setPrice(5200);
int actual = goodsDao.saveGoods(goods);
assertEquals(1,actual);
}


@Test
public void testDeleteGoodsById(){
int id = 1;
int actual = goodsDao.deleteGoodsById(id);
assertEquals(1,actual);
}

@Test
public void testUpdateGoodsById1(){
Goods goods = new Goods();
goods.setGoodsId(2);
goods.setPrice(3250.20);
Map<String,Object> map = new HashMap<String,Object>();
map.put("price",5521);
map.put("id",2);
int actual = goodsDao.updateGoodsById(map);
assertEquals(1,actual);
}


@Test
public void testUpdateGoodsById(){
Goods goods = new Goods();
goods.setGoodsId(2);
goods.setPrice(36.20);
int actual = goodsDao.updateGoodsById(goods);
assertEquals(1,actual);
}





}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值