摘录自:http://blog.csdn.net/y172158950/article/details/16979391
新的项目中用到mybatis,虽然不用自己写ORM的代码,但是借这个机会,学习一下。
本章目标:如题,helloWorld。
方法:在CSDN上下载一个demo,简单修改,能跑起来就OK。
1. 环境
a)用到的jar:mybatis-3.0.5.jar ,MySQL-connector-java-5.0.8-bin.jar (只有一个jar,是不是很简单)
b)mysql
c)demo下载路径:http://download.csdn.net/detail/lihonghua168/3579586#comment
2.demo代码目录:
a)configuration.xml :mysql连接配置;基本就2块,一个是数据库连接配置,二是映射实体,相关映射文件。
- <?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 type="com.test.Goods"/>
- </typeAliases>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"></transactionManager>
- <dataSource type="POOLED">
- <property name="driver"
- value="com.mysql.jdbc.Driver" />
- <property name="url"
- value="jdbc:mysql://127.0.0.1:3306/test" />
- <property name="username" value="root" />
- <property name="password" value="root" />
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <!-- 数据连接成功后执行的对应实体映射文件数据库语句 -->
- <mapper resource="com/test/Mapper.xml" />
- </mappers>
- </configuration>
b)Mapper.xml :sql语句配置文件;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.test.Mapper">
- <select id="selectGood" parameterType="int" resultType="Goods">
- select * from test where id =#{id}
- </select>
- <insert id="insertGood" parameterType="com.test.Goods" useGeneratedKeys="true" keyProperty="id"><!-- 后面两个表示主键自动生成的 -->
- insert into test (cateId , name , password , price , description , orderNo , updateTime) values(#{cateId} , #{name} , #{password} , #{price} , #{description} , #{orderNo} , #{updateTime});
- </insert>
- <delete id="deleteGood" parameterType="int">
- delete from test where id=#{id}
- </delete>
- <update id="updateGood" parameterType="com.test.Goods">
- update test set name=#{name},password=#{password},description=#{description},updateTime=#{updateTime} where id=#{id}
- </update>
- </mapper>
c)Goods.java :结果集与表映射类;和hibernate不同,没有哪里写表与实体的映射关系(存疑)。
- package com.test;
- import java.util.Date;
- /**
- * 实体,作为映射时的数据,所以所有字段的名称都必须和数据库里面的一样,不管什么数据库
- *
- *对应数据库表:
- create table test.test (
- id bigint(10) primary key AUTO_INCREMENT,
- cateId varchar(100),
- name varchar(100),
- password varchar(100),
- price double,
- description varchar(100),
- orderNo int,
- updateTime datetime
- );
- */
- public class Goods {
- private long id;
- private String cateId;
- private String name;
- private String password;
- private double price;
- private String description;
- private int orderNo;
- private Date updateTime;
- public String getCateId() {
- return cateId;
- }
- public long getId() {
- return id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public void setCateId(String cateId) {
- this.cateId = cateId;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public double getPrice() {
- return price;
- }
- public void setPrice(double price) {
- this.price = price;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public int getOrderNo() {
- return orderNo;
- }
- public void setOrderNo(int orderNo) {
- this.orderNo = orderNo;
- }
- public Date getUpdateTime() {
- return updateTime;
- }
- public void setUpdateTime(Date updateTime) {
- this.updateTime = updateTime;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
d)Test1.java :dao类,测试类
- package com.test;
- import java.io.IOException;
- import java.io.Reader;
- import java.util.Date;
- 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 Test1{
- public static void main(String args[]) throws IOException {
- String resource = "com/test/configuration.xml";//获得xml(Mybatis)数据库连接的连接
- Reader reader = Resources.getResourceAsReader(resource);//读取里面的文件
- SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
- .build(reader);//创建session工厂
- SqlSession session = sessionFactory.openSession();//打开session
- new Test1().insert(session);
- }
- /**
- * 修改
- * @param session
- */
- public void update(SqlSession session){
- int falg=0;
- Goods g=new Goods();
- g.setId(1);
- g.setCateId("2");
- g.setName("huage");
- g.setPassword("huage");
- g.setDescription("He is me");
- g.setUpdateTime(new Date());
- falg=session.update("com.test.Mapper.updateGood", g);
- session.commit();
- if(falg==1){
- System.out.println("Data update successfully!");
- }else{
- System.out.println("Data update fail..");
- }
- session.close();
- }
- /**
- * 删除
- * @param session
- */
- public void delete(SqlSession session){
- //session.delete("1");
- int falg=0;
- falg=session.delete("com.test.Mapper.deleteGood", 1);
- session.commit();
- if(falg==1){
- System.out.println("Data delete successfully!");
- }else{
- System.out.println("Data dalete fail..");
- }
- session.close();
- }
- /**
- * 插入数据
- * @param session
- */
- public void insert(SqlSession session){
- Goods g=new Goods();
- g.setCateId("2");
- g.setName("huage");
- g.setPassword("huage");
- g.setPrice(5);
- g.setDescription("He is me");
- g.setOrderNo(2);
- g.setUpdateTime(new Date());
- int flag=0;
- flag=session.insert("com.test.Mapper.insertGood",g);
- session.commit();//一定要提交才能插入数据
- if(flag==1){
- System.out.println("Data inserted successfully!");
- }else{
- System.out.println("Data inserted fails!");
- }
- session.close();
- }
- /**
- * 查询
- * @param session
- */
- public void select(SqlSession session){
- try {
- Goods goods = (Goods) session.selectOne("com.test.Mapper.selectGood", 1);//执行数据操作
- System.out.println("good name is : " + goods.getName());
- System.out.println("description :="+goods.getDescription());
- System.out.println("orderNo :="+goods.getOrderNo());
- System.out.println("price :="+goods.getPrice());
- System.out.println("updateTiem :="+goods.getUpdateTime());
- System.out.println("id :="+goods.getId());
- System.out.println("password :="+goods.getPassword());
- System.out.println("cateid :="+goods.getCateId());
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
- }
e)Test1.java流程分析
i. 通过Reader类读取configuration.xml类容,获取数据库连接配置及相关实体类、sql语句配置信息。
ii. 依据Reader的信息创建SqlSessionFactory。(这2步在实际工程中调用一次即可)
iii. 创建SqlSession,相当于JDBC的Connection
iv. insert数据:封装了sql语句,封装了映射过程(update,remove,select过程类似)
1)封装Goods实体。
2)调用session.insert方法:2个参数,"com.test.Mapper.insertGood“,去Mapper.xml找下,insert语句已经写好了;g,实体
3)commit,close连接。