Mybatis实现CRUD

实现Mybatis的CRUD

一:创建一个项目,第一步还是导包,在lib文件中放入所需要的jar包
mybatis-3.1.1.jar
mysql-connector–java-8.0.19.jar

二:在数据库中建立两个表persons,orders,建立的表如下图所示:
在这里插入图片描述
在这里插入图片描述
三:在项目的src文件夹下创建实体类,项目包试图如下所示:
在这里插入图片描述
Person的实体类代码如下所示:

package com.bean;

import java.util.List;

public class Person {
	private int pid;
	
	private String name;
	
	
	private List<Order> orders;
	
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public List<Order> getOrders() {
		return orders;
	}
	public void setOrders(List<Order> orders) {
		this.orders = orders;
	}
	@Override
	public String toString() {
		return "Person [pid=" + pid + ", name=" + name + ", orders=" + orders + "]";
	}

}

Order的实体类代码如下所示:

package com.bean;

public class Order {
private int orderid;
private int total;
public int getOrderid() {
	return orderid;
}
public void setOrderid(int orderid) {
	this.orderid = orderid;
}
public int getTotal() {
	return total;
}
public void setTotal(int total) {
	this.total = total;
}
@Override
public String toString() {
	return "Order [orderid=" + orderid + ", total=" + total + "]";
}

}

第四步:创建conf.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.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/j115?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT&amp;nullCatalogMeansCurrent = true" />
                <property name="username" value="root" />
                <property name="password" value="xiaoyang123" />
            </dataSource>
        </environment>
    </environments>
</configuration>

第五步:创建personMapperI接口文件实现Mybatis的CRUD(第一种实现,根据接口实现)(注意:对于这里面的sql语句,最好在数据库前端软件运行一下,看是否能正常运行,这是一个好习惯

package com.mapping;
/**
 * 基于注解去实现
 * 
 */
import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.bean.Person;

public interface personMapperI {
	 @Insert("insert into persons(name) values(#{name})")
	 public int add(Person person);
	 
	//使用@Delete注解指明deleteById方法要执行的SQL
	    @Delete("delete from persons where pid=#{pid}")
	    public int deleteById(int pid);

	    //使用@Update注解指明update方法要执行的SQL
	    @Update("update persons set name=#{name} where pid=#{pid}")
	    public int update(Person person);

	    //使用@Select注解指明getById方法要执行的SQL
	    @Select("select * from persons where pid=#{pid}")
	    public Person getById(int pid);

	    //使用@Select注解指明getAll方法要执行的SQL
	    @Select("select * from persons")
	    public List<Person> getAll();	    
}

第六步:(特别注意,也是最重要的事情
在conf.xml中注册personMapperI,如下所示:

<?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.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/j115?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT&amp;nullCatalogMeansCurrent = true" />
                <property name="username" value="root" />
                <property name="password" value="xiaoyang123" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
         <mapper class="com.mapping.personMapperI"/>  <!--用完全限定类名  -->
    </mappers>
</configuration>

第七步:在src下创建com.test包,编写test.java类

package com.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.bean.Person;
import com.mapping.personMapperI;
import com.util.MyBatisUtil;

public class Test {
	public void testAdd(){    //增加数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
        personMapperI mapper = sqlSession.getMapper(personMapperI.class);
        Person person = new Person();
        person.setName("Jerry");
        int add = mapper.add(person);
        sqlSession.close();
        System.out.println(add);   
    }
	
    public void testUpdate(){  //修改数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
        personMapperI mapper = sqlSession.getMapper(personMapperI.class);
        Person person= new Person();
        person.setPid(3);
        person.setName("xiaoyang");
        int retResult = mapper.update(person);
        sqlSession.close();
        System.out.println(retResult);
    }


    public void testDelete(){   //删除数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
        personMapperI mapper = sqlSession.getMapper(personMapperI.class);
        int retResult = mapper.deleteById(3);
        sqlSession.close();
        System.out.println(retResult);
    }

    
    public void testGetUser(){  //根据id查询数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        personMapperI mapper = sqlSession.getMapper(personMapperI.class);
        Person person = mapper.getById(1);
        sqlSession.close();
        System.out.println(person);
    }

    
    public void testGetAll(){   //查询所有数据
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        personMapperI mapper = sqlSession.getMapper(personMapperI.class);
        List<Person> lstPersons = mapper.getAll();
        sqlSession.close();
        System.out.println(lstPersons);
    }
    
	
	public static void main(String[] args) { 
		Test1 test=new Test1();
		//test.testAdd();
		//test.testUpdate();
		//test.testDelete();
		//test.testGetUser();
		//test.testGetAll();
		
	}
}

附MyBatisUtil.java,这个类我是根据另外一位博主,他的名字叫孤傲苍狼,地址为:
点击这里进入这位作者的博客,我个人认为这个博主的文章质量很高,大家可以浏览一下
代码如下:

package com.util;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

    /**
     * 获取SqlSessionFactory
     * @return SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        String resource = "conf.xml";
        InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        return factory;
    }

    /**
     * 获取SqlSession
     * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }

    /**
     * 获取SqlSession
     * @param isAutoCommit
     *         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
     *         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
     * @return SqlSession
     */
    public static SqlSession getSqlSession(boolean isAutoCommit) {
        return getSqlSessionFactory().openSession(isAutoCommit);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值