本文主要是介绍利用mybatis实现增删改查 的小项目,单表,双表一对多,,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简介:
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于”internet”和”abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)
MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。
下面开始我们的小项目:
1.我们已经在自己的数据库中建立好了将要展示的三个表,并添加好了某些数据
user表:
CREATE TABLE `user` (`id` INT(11) NOT NULL AUTO_INCREMENT,`username` VARCHAR(50) NOT NULL COLLATE 'utf8_bin',`psw` VARCHAR(50) NOT NULL COLLATE 'utf8_bin',PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=12
;
Company表:
CREATE TABLE `company` (`cid` INT(11) NOT NULL,`name` VARCHAR(10) NOT NULL COLLATE 'utf8_bin',`address` VARCHAR(10) NOT NULL COLLATE 'utf8_bin',`pro` VARCHAR(10) NOT NULL COLLATE 'utf8_bin',`city` VARCHAR(10) NOT NULL COLLATE 'utf8_bin',`price` FLOAT NULL DEFAULT NULL,PRIMARY KEY (`cid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
Emp表:
CREATE TABLE `emp` (`eid` INT(11) NOT NULL,`name` VARCHAR(10) NOT NULL COLLATE 'utf8_bin',`sex` VARCHAR(2) NULL DEFAULT NULL,`email` VARCHAR(50) NULL DEFAULT NULL,`salary` FLOAT NULL DEFAULT NULL,`cid` INT(11) NULL DEFAULT NULL,PRIMARY KEY (`eid`),INDEX `c_e_cid` (`cid`),CONSTRAINT `c_e_cid` FOREIGN KEY (`cid`) REFERENCES `company` (`cid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
company和emp是一对多的关系
2.通过帮助文档,建立核心MyBatis配置文件generator.xml,
在该文件中已经告诉MyBatis所链接的数据库,所使用哪种方式对数据表进行映射。以及一些其他信息。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration><!-- 数据库驱动包位置 --><!-- <classPathEntry location="C:\Users\fangjiejie\.IntelliJIdea2016.1\config\jdbc-drivers\mysql-connector-java-5.1.35.jar" /> --><classPathEntry location="C:\Users\fangjiejie\.IntelliJIdea2016.1\config\jdbc-drivers\mysql-connector-java-5.1.35-bin.jar" /><context id="mysqltools" targetRuntime="MyBatis3"><commentGenerator><property name="suppressAllComments" value="true" /></commentGenerator><!-- 数据库链接URL、用户名、密码 --><!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sy" userId="sypro" password="sypro"> --><jdbcConnection driverClass="org.gjt.mm.mysql.Driver" connectionURL="jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8" userId="root" password="******"></jdbcConnection><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- 生成模型的包名和位置 --><javaModelGenerator targetPackage="com.lyf.model" targetProject="D:\web\mybitsUse"><property name="enableSubPackages" value="true" /><property name="trimStrings" value="true" /></javaModelGenerator><!-- 生成的映射文件包名和位置 --><sqlMapGenerator targetPackage="com.lyf.mapping" targetProject="D:\web\mybitsUse"><property name="enableSubPackages" value="true" /></sqlMapGenerator><!-- 生成DAO的包名和位置 --><javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.lyf.mapper" targetProject="D:\web\mybitsUse"><property name="enableSubPackages" value="true" /></javaClientGenerator><!-- 要生成那些表(更改tableName和domainObjectName就可以)更复杂的方式如下: 但基本不常用<table tableName="tmenu" domainObjectName="Menu" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />--><table tableName="company" domainObjectName="Company" /><table tableName="emp" domainObjectName="Emp" /><table tableName="user" domainObjectName="User" /></context>
</generatorConfiguration>
3.将generator.xml文档和mybatis的jar 置于某个目录下,本例目录为:D:\web\mybitsUse
4.由java命令生成model,mappper
命令为:java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
就会在当前目录下生成我们需要的目录com
5.建立一个maven项目
在pom.xml中要加入jar包
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.31</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency>
6.将我们建立好的com目录移到maven项目中,
7.建立好resources下的资源配置文档mybatis.cfg.xml
注意标清链接的数据库,mapper映射之类
<?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="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="******" /></dataSource> </environment> </environments> <mappers><mapper class="com.lyf.mapper.CompanyMapper"/><mapper class="com.lyf.mapper.EmpMapper"/><mapper class="com.lyf.mapper.UserMapper"/></mappers> </configuration>
8.整个项目的目录结构就建立好了
9.下面实现单表操作的增删改查
package com.lyf.service;import com.lyf.model.User;
import com.lyf.model.UserExample;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import java.util.List;/*** Created by fangjiejie on 2017/5/29.*/
public class UserServiceImp {SqlSessionFactory ssf;public UserServiceImp() {ssf=new SqlSessionFactoryBuilder().build(this.getClass().getClassLoader().getResourceAsStream("mybatis.cfg.xml"));}public static void main(String[] args) {new UserServiceImp();}
@Testpublic void add(){SqlSession sqlSession=ssf.openSession();User user=new User();user.setUsername("lyf");user.setPsw("hahaha");sqlSession.insert("com.lyf.mapper.UserMapper.insert",user);sqlSession.commit();sqlSession.close();}@Testpublic void del(){SqlSession sqlSession=ssf.openSession();User user=new User();user.setId(8);sqlSession.delete("com.lyf.mapper.UserMapper.deleteByPrimaryKey",user);//sqlSession.delete("com.lyf.mapper.UserMapper.deleteByPrimaryKey",8);sqlSession.commit();sqlSession.close();}@Testpublic void Update(){SqlSession sqlSession=ssf.openSession();User user=new User();user.setId(11);user.setUsername("hahahaaa");sqlSession.update("com.lyf.mapper.UserMapper.updateByPrimaryKeySelective",user);sqlSession.commit();sqlSession.close();}@Testpublic void selectUser(){SqlSession sqlSession=ssf.openSession();UserExample userExample=new UserExample();userExample.createCriteria().andUsernameLike("l%");List<User> list= sqlSession.selectList("com.lyf.mapper.UserMapper.selectByExample",userExample);for(User u:list){System.out.println(u.getUsername());}sqlSession.close();}
}
10.下面演示主从表一对多,多对一的查询
1.在Company类中添加属性对象elist(emp的集合),并作getter和setter
private Object elist;public Object getElist() {return elist;}public void setElist(Object elist) {this.elist = elist;}
在Emp类中添加对象属性comp(company),并做getter和setter
private Object comp;public Object getComp() {return comp;}public void setComp(Object comp) {this.comp = comp;}
2.在mapper中添加修改映射关系,添加映射方法
CompanyMapper类
修改:@Select({"select","cid, name, address, pro, city, price","from company","where cid = #{cid,jdbcType=INTEGER}"})@Results({@Result(column="cid", property="cid", jdbcType=JdbcType.INTEGER, id=true),@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),@Result(column="address", property="address", jdbcType=JdbcType.VARCHAR),@Result(column="pro", property="pro", jdbcType=JdbcType.VARCHAR),@Result(column="city", property="city", jdbcType=JdbcType.VARCHAR),@Result(column="price", property="price", jdbcType=JdbcType.REAL),@Result(property="elist",javaType = List.class,column="cid",many = @Many(select="com.lyf.mapper.EmpMapper.selectEmpByCom"))})Company selectByPrimaryKey(Integer cid);
添加selectComByEmp方法:@Select({"select","cid, name, address, pro, city, price","from company","where cid = #{cid,jdbcType=INTEGER}"})@Results({@Result(column="cid", property="cid", jdbcType=JdbcType.INTEGER, id=true),@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),@Result(column="address", property="address", jdbcType=JdbcType.VARCHAR),@Result(column="pro", property="pro", jdbcType=JdbcType.VARCHAR),@Result(column="city", property="city", jdbcType=JdbcType.VARCHAR),@Result(column="price", property="price", jdbcType=JdbcType.REAL)})Company selectComByEmp(Integer cid);
EmpMapper类:
修改:@Select({"select","eid, name, sex, email, salary, cid","from emp","where eid = #{eid,jdbcType=INTEGER}"})@Results({@Result(column="eid", property="eid", jdbcType=JdbcType.INTEGER, id=true),@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),@Result(column="sex", property="sex", jdbcType=JdbcType.VARCHAR),@Result(column="email", property="email", jdbcType=JdbcType.VARCHAR),@Result(column="salary", property="salary", jdbcType=JdbcType.REAL),@Result(column="cid", property="cid", jdbcType=JdbcType.INTEGER),@Result(property = "comp",column="cid",one = @One(select="com.lyf.mapper.CompanyMapper.selectComByEmp"))})Emp selectByPrimaryKey(Integer eid);添加selectEmpByCom方法:@Select({"select","eid, name, sex, email, salary, cid","from emp","where cid = #{cid,jdbcType=INTEGER}"})@Results({@Result(column="eid", property="eid", jdbcType=JdbcType.INTEGER, id=true),@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),@Result(column="sex", property="sex", jdbcType=JdbcType.VARCHAR),@Result(column="email", property="email", jdbcType=JdbcType.VARCHAR),@Result(column="salary", property="salary", jdbcType=JdbcType.REAL),@Result(column="cid", property="cid", jdbcType=JdbcType.INTEGER)})List<Emp> selectEmpByCom(Integer cid);
测试代码:
package com.lyf.service;import com.lyf.model.Company;
import com.lyf.model.Emp;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import java.util.List;/*** Created by fangjiejie on 2017/5/29.*/
public class CompanyServiceImp {private SqlSessionFactory ssf;public CompanyServiceImp(){ssf= new SqlSessionFactoryBuilder().build(this.getClass().getClassLoader().getResourceAsStream("mybatis.cfg.xml"));}@Testpublic void queryEmpByCompany(){SqlSession session=ssf.openSession();Company company=new Company();company.setCid(1);Company company1=session.selectOne("com.lyf.mapper.CompanyMapper.selectByPrimaryKey",company);List<Emp> list=(List<Emp>)company1.getElist();for(Emp e:list){System.out.println(e.getName());}session.close();}//运行结果:MIKEJACK@Testpublic void queryComByEmp(){SqlSession session=ssf.openSession();Emp emp1=session.selectOne("com.lyf.mapper.EmpMapper.selectByPrimaryKey",4);List<Company> company=(List<Company>) emp1.getComp();System.out.println(company.get(0).getName());session.close();}}
//运行结果:
京东
这篇关于利用mybatis实现增删改查 的小项目,单表,双表一对多,的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!