Maven是专门用于管理和构建Java项目的工具,它的主要功能有:
Maven提供了标准化的项目结构,所有IDE使用Maven构建的项目结构完全一样,所有IDE创建的Maven项目可以通用
Apache Maven 是一个项目管理和构建工具,它基于项目对象模型(POM)的概念,通过一小段描述信息来管理项目的构建、报告和文档
官网:
当项目中使用坐标引入依赖jar包后,首先会查找本地仓库中是否有对应的jar包:
还可以搭建远程仓库,将来jar包的查找顺序则变为:
Maven 安装配置
apache-maven-3.6.1.rar
既安装完成(注意版本适配)MAVEN_HOME
为安装路径的bin目录conf/settings.xml
中的
为一个指定目录conf/settings.xml
中的
标签,为其添加如下子标签:Maven构建项目生命周期描述的是一次构建过程经历经历了多少个事件
Maven对项目构建的生命周期划分为3套
IDEA 配置 Maven
什么是坐标?
Maven 坐标主要组成:
导入msql驱动jar包
该行如果红字,在设置里的构建、执行、部署中的构建工具点击如下:
自动配置如下:
方案二:使用坐标导入jar包 - 快捷方式
在Test测试里,当使用driver看到测试里面出现JDBC里面的driver,说明测试环境确实有效
而不使用时,在编译环境是不会出现JDBC的,而是sql里面自带的
2.provied
在编译环境下也有效
什么是MyBatis?
MyBatis是一款优秀的持久层框架
,用于简化JDBC 开发
MyBatis 本是Apache的一个开源项目iBatis, 2010年这个项目由apache softwarefoundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github
MyBaits官网
持久层
框架
create database mybatis;
use mybatis;
drop table if exists tb_user;
create table tb_user(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
gender char(1),
addr varchar(30)
);
insert into tb_user values (1,'张三','123','男','广door');
insert into tb_user values (2,'李四','234','女','北京');
insert into tb_user values (3,'王五','11','男','新日暮里');
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>mybatis-demoartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.46version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.20version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.3version>
dependency>
dependencies>
project>
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %npattern>
encoder>
appender>
<logger name="com.itheima" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
logger>
<root level="DEBUG">
<appender-ref ref="Console"/>
root>
configuration>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
configuration>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="selectAll" resultType="com.itheima.pojo.User">
select * from tb_user;
select>
mapper>
package com.itheima.pojo;
public class User {
private Integer id;
private String username;
private String password;
private String gender;
private String addr;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
package com.itheima;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
//1.加载mybatis的核心配置文件,获取SqlSessionFactiory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.执行sql
List<User> users = sqlSession.selectList("test.selectAll");
System.out.println(users);
//4.释放资源
sqlSession.close();
}
}
成功连接获取
产生原因::ldea和数据库没有建立连接;不识别表信息
解决方式:在ldea中配置MySQL数据库连接
目的:
实现:使用Mapper代理方式完成入门案例:
首先定义一个接口,让mapper文件和这个接口在同一个目录下有两种做法
① 是直接拖过来,但是这样做并不好,因为将来在项目里面会要求java代码和配置文件分开
可以先编译生成一个class目录:
点开com,
配置文件应该放到该目录下
② 是在resources下建立一个一样包的结构就行,但是注意:
此时新建目录时,不要用.
来分割命名,
这样写的话不会分层,就不是一个包的结构,应该用/
,之后把mapper文件拖入该包中,然后编译
成功实现mapper接口和sql映射文件在同一目录下
- 通过SqlSession的getMapper方法获取Mapper接口的代理对象
- 通用对应方法完成sql的执行
public interface UserMapper {
//因为UserMapper文件里面有个id是selectAll,所以在接口里面要有个方法叫selectAll的,而且参数的返回类型要一致
//但是由于要查出来的是一个集合,不能写User selectAll();,这样就只能查出一个对象,这个就根据sql语句来判断
List<User> selectAll();
}
mybatis-config.xml载入路径:
User.Mapper.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMapper">
<select id="selectAll" resultType="com.itheima.pojo.User">
select * from tb_user;
select>
mapper>
实现类MybatisDemo2:
//代理开发
public class MyBatisDemo2 {
public static void main(String[] args) throws IOException {
//1.加载mybatis的核心配置文件,获取SqlSessionFactiory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.执行sql,代理开发就不需要调用sqlSession.selectList来执行sql了
//List users = sqlSession.selectList("test.selectAll");
//获取UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
System.out.println(users);
//4.释放资源
sqlSession.close();
}
}
细节:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载
细节:配置各个标签时,需要遵守前后顺序
mybatis-config核心配置文件内容:
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.itheima.mapper"/>
mappers>
configuration>
environments:配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment
而后面的default表示默认使用的环境
默认环境又是什么?
是当使用mybatis创建SqlSessionFactry对象的时候,没有指定的环境的话,默认使用哪个环境
创建SqlSessionFactory有两种方式,一种是直接用创建好的SqlSessionBuilder对象,sqlSessionFactoryBuilder.build(Resources.getResourceAsStream(“mybatis-config.xml”));创建
还有一种build方法就是在上述build方法后面参数加一个指定的environment属性值,这样就是可以指定用的environment而不是用default里面的默认环境
MybatisX是一款基于IDEA的快速开发插件,为效率而生。
主要功能:
优点:
要完成的功能列表清单:
1、查询
2、添加
3、修改
4、删除
drop table if exists tb_brand;
create table tb_brand(
id int primary key auto_increment,
brand_name varchar(20),
company_name varchar(20),
ordered int,
description varchar(100),
-- 状态:0禁用 1启用
status int
);
insert into tb_brand (brand_name,company_name,ordered,description,status)
values('三只松鼠','三只松鼠有限公司',5,'好吃不上火',0),
('华为','华为有限公司',100,'实现技术',1),
('小米','小米有限公司',50,'are you ok',1);
select * from tb_brand
@Alias("brand")//用于忽略mybatis的设置报错
public class Brand {
private Integer id;
private String brandName;
private String companyName;
private Integer ordered;
private String description;
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">
<select id="selectAll" resultType="brand">
select * from tb_brand ;
select>
mapper>
BrandMapper.java:
public interface BrandMapper {
// 查询所有
public List<Brand> selectAll();
}
Brand测试类:
public class MyBatisTest {
@Test
public void testSelectAll() throws IOException {
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
List<Brand> brands = brandMapper.selectAll();
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
}
但是为什么名字会出现null呢?
因为java里的Brand类命名比如是brandName驼峰命名,但是sql里面的命名是brand_name,字段规范不一样,就对应不上
方案:
标签
标签中,使用resultMap属性替换resultType属性
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
resultMap>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand ;
select>
mapper>
@Test
public void testSelectById() throws IOException {
//接收id
int id = 1;
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
Brand brand = brandMapper.selectById(id);
System.out.println(brand);
//5.释放资源
sqlSession.close();
}
参数占位符:
1.#{}:会将其替换喂?,为了防止sql注入
2.${}:拼sql。会存在sql注入的问题
3. 使用时机:
参数传递的时候用:#{}
表名或者列名不固定的情况下用:${} 但存在SQL注入
参数类型:parameterType:可以省略
特殊字符处理:
1.转义字符
2.CDATA区
@Test
public void testSelectByCondition() throws IOException {
//接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";
// 处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
@Test
public void testSelectByCondition() throws IOException {
//接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";
// 处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
List<Brand> brands = brandMapper.selectByCondition(brand);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
@Test
public void testSelectByCondition() throws IOException {
//接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";
// 处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
Map map = new HashMap<>();
map.put("status",status);
map.put("companyName",companyName);
map.put("brandName",brandName);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
List<Brand> brands = brandMapper.selectByCondition(map);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
小结:
但是该查询有缺点:就是条件要写满才能查询处理,但是在一般的业务中需要的是只要一个关键词就能查出来
此时就需要动态查询
SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL
if:条件判断,test:用来写逻辑表达式
@Test
public void testSelectByCondition() throws IOException {
//接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";
// 处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
Map map = new HashMap<>();
// map.put("status",status);
map.put("companyName",companyName);
// map.put("brandName",brandName);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
List<Brand> brands = brandMapper.selectByCondition(map);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
但是这样无法做到动态查询,因为如果第一个条件不存在了,后面直接跟and就直接出问题了
解决问题:
在业务当中,根据用户在多个条件中选择其中一个条件的不同,然后在搜索框里面输入关键字进行查询,进而生成
@Test
public void testSelectByConditionSingle() throws IOException {
//接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";
// 处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
Brand brand = new Brand();
brand.setStatus(status);
// brand.setCompanyName(companyName);
// brand.setBrandName(brandName);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
List<Brand> brands = brandMapper.selectByConditionSingle(brand);
System.out.println(brands);
//5.释放资源
sqlSession.close();
}
可见sql语句条件只有一个
但是这样有一个问题,当用户不选择条件而是直接采用搜索关键字的时候,这样写就会报错
例如:
解决方案:
@Test
public void testAdd() throws IOException {
//接收参数
int status = 1;
String companyName = "麻瓜手机";
String brandName = "麻瓜";
String description = "乖乖站好";
int ordered = 100;
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.add(brand);
//之后一定要提交事务,因为jdbc设置了系统手动提交,没有提交事务的话会回滚
//提交事务
sqlSession.commit();//or 先前在上面SqlSession sqlSession = sqlSessionFactory.openSession(true);
//5.释放资源
sqlSession.close();
}
@Test
public void testAdd2() throws IOException {
//接收参数
int status = 1;
String companyName = "麻瓜手机";
String brandName = "麻瓜";
String description = "乖乖站好";
int ordered = 100;
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.add(brand);
//之后一定要提交事务,因为jdbc设置了系统手动提交,没有提交事务的话会回滚
Integer id = brand.getId();
System.out.println(id);
//提交事务
sqlSession.commit();//or 先前在上面SqlSession sqlSession = sqlSessionFactory.openSession(true);
//5.释放资源
sqlSession.close();
}
@Test
public void testUpdate() throws IOException {
//接收参数
int status = 1;
String companyName = "楞头手机";
String brandName = "楞头";
String description = "捞的嘛不谈";
int ordered = 200;
int id =5;
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
brand.setId(id);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
int count = brandMapper.update(brand);
System.out.println(count);
//提交事务
sqlSession.commit();//or 先前在上面SqlSession sqlSession = sqlSessionFactory.openSession(true);
//5.释放资源
sqlSession.close();
}
sql语句只能适应于修过所有的字段,不能做到通用性,如果只想该某个字段其他字段不变的话,一旦更新其他的就会变成了null
@Test
public void testUpdate() throws IOException {
//接收参数
int status = 0;
String companyName = "楞头手机";
String brandName = "楞头";
String description = "捞的嘛不谈";
int ordered = 200;
int id =5;
Brand brand = new Brand();
brand.setStatus(status);
// brand.setCompanyName(companyName);
// brand.setBrandName(brandName);
// brand.setDescription(description);
// brand.setOrdered(ordered);
brand.setId(id);
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
int count = brandMapper.update(brand);
System.out.println(count);
//提交事务
sqlSession.commit();//or 先前在上面SqlSession sqlSession = sqlSessionFactory.openSession(true);
//5.释放资源
sqlSession.close();
}
@Test
public void testDeleteById() throws IOException {
//接收参数
int id =5;
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.deleteById(id);
//提交事务
sqlSession.commit();//or 先前在上面SqlSession sqlSession = sqlSessionFactory.openSession(true);
//5.释放资源
sqlSession.close();
}
mybatis会将数组参数,封装为一个Map集合:
@Test
public void testDeleteByIds() throws IOException {
//接收参数
int[] ids = {3,4};
//1.获取SqlSessionFactory,加载mybatis的核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取Sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.deleteByIds(ids);
//提交事务
sqlSession.commit();//or 先前在上面SqlSession sqlSession = sqlSessionFactory.openSession(true);
//5.释放资源
sqlSession.close();
}
MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对应这些参数进行不同的封装处理方式
map.put("arg0",Collection集合)
map.put("collection",Collection集合)
map.put("arg0",数组)
map.put("array",数组)
map.put("arg0",数组)
map.put("array",数组)
map.put("arg0",参数1)
map.put("param1",参数1)
map.put("arg1",参数2)
map.put("param2",参数2)
-------------@Param("username")
map.put("username",参数1)
map.put("param1",参数1)
map.put("arg1",参数2)
map.put("param2",参数2)
使用注解开发会比配置文件开发更加方便
@Select("select * from tb_user where id = #{id}")
public User selectByld(int id);
提示:
使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java注解不仅力不从心,还会址你本就复杂的SQL语句更加期乱不堪。因此。如果你需要的一些很亮杂的涯作,最好用XML来映射语句。
选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和XML的语句映射方式间自由移植和切换。