MyBatis的参数传递
主要参考代码:
BookMapper:
package com.yzh7.mapper;
import com.yzh7.entity.Book;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface BookMapper {
//mybatis传参问题
//1.传入一个参数:在mapper中可以用任意名字引用这个参数
Book getById(Integer bookId);
//2.传入多个基本类型参数:在mapper中无法通过参数名引用参数
// 解决方法:1) 通过arg0,arg1... param1,param2...
// 2) 通过@Param注解为方法参数设置参数mybatis能够引用的参数名
Book getByNameAndAuthor(@Param("bn") String bookName,
@Param("at") String author);
//3.传入对象:可以在mapper中直接应用对象属性
Book getByMap(Map map);
//4.传入对象:可以在mapper中直接应用对象属性
Book getByBook(Book book);
//5.区别#{},${}: 模糊查询
// #{}:用参数占位的方式设置数据。不会有注入问题,但是不能用拼接方式拼接sql
// ${}:直接用拼接sql的方式,拼接数据。有sql注入问题。一般用${value}引用单个参数值
List<Book> listByBookName(String bookName);
//查询
List<Map> listAll();
List<Book> listAll2();
//添加
int insert(Book book);
//修改
int update(Book book);
//删除
int delete(Integer bookId);
}
BookMapper.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.yzh7.mapper.BookMapper">
<!--根据mapper接口中的方法定义增删改查-->
<select id="listAll" resultType="map">
select * from tb_book
</select>
<select id="listAll2" resultType="book">
select * from tb_book
</select>
<select id="getById" parameterType="int" resultType="book">
select * from tb_book
where book_id = #{bookId}
</select>
<select id="getByNameAndAuthor" resultType="book">
select * from tb_book
where book_name=#{bn} and author=#{at}
</select>
<select id="getByMap" parameterType="map" resultType="book">
select * from tb_book
where book_name=#{bookName} and author=#{author}
</select>
<select id="getByBook" parameterType="book" resultType="book">
select * from tb_book
where book_name=#{bookName} and author=#{author}
</select>
<select id="listByBookName" resultType="book">
select * from tb_book
where book_name like '%${value}%'
</select>
<insert id="insert" parameterType="book">
insert into tb_book
(book_name,author,price,publisher,pub_date)
values
(#{bookName},#{author},#{price},#{publisher},#{pubDate})
</insert>
</mapper>
demo2:
package com.yzh7.test;
import com.yzh7.entity.Book;
import com.yzh7.mapper.BookMapper;
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 org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author: hy
* @create: 2022-08-15 10:33:45
*/
public class Demo2 {
@Test
public void test1() throws NoSuchMethodException {
BookMapper bm = session.getMapper(BookMapper.class);
//1.传入一个参数:在mybatis中可以用任意名字引用这个参数
Book book = bm.getById(1);
System.out.println(book);
}
@Test
public void test2() throws NoSuchMethodException {
BookMapper bm = session.getMapper(BookMapper.class);
//2.传入多个基本类型参数:在mybatis中无法通过参数名引用参数
// 正确引用方式: ary0,ary1....
// param1,param2
Book book = bm.getByNameAndAuthor("图书1","作者1");
System.out.println(book);
}
@Test
public void test3() throws NoSuchMethodException {
BookMapper bm = session.getMapper(BookMapper.class);
//3.传入对象:可以在mapper中直接应用对象属性
Map map = new HashMap();
map.put("bookName","图书1");
map.put("author","作者1");
Book book =bm.getByMap(map);
System.out.println(book);
}
@Test
public void test4() throws NoSuchMethodException {
BookMapper bm = session.getMapper(BookMapper.class);
//4.传入对象:可以在mapper中直接应用对象属性
Book b = new Book();
b.setBookName("图书1");
b.setAuthor("作者1");
Book book =bm.getByBook(b);
System.out.println(book);
}
@Test
public void test5() throws NoSuchMethodException {
BookMapper bm = session.getMapper(BookMapper.class);
//5.区别#{},${}: 模糊查询
// #{}:用参数占位的方式设置数据。不会有注入问题,但是不能用拼接方式拼接sql
// ${}:直接用拼接sql的方式,拼接数据。有sql注入问题。一般用${value}引用单个参数值
List<Book> bookList = bm.listByBookName("图");
System.out.println(bookList);
}
//会话工厂
private static SqlSessionFactory factory;
//会话
private SqlSession session;
@BeforeClass
public static void befCls() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
}
@Before
public void bf(){
session = factory.openSession();
}
@After
public void af(){
//提交事务
session.commit();
//关闭会话
session.close();
}
}
运行结果展示:
数据库/数据表:
Book getById(Integer bookId);
//1.传入一个参数:在mybatis中可以用任意名字引用这个参数
//2.传入多个基本类型参数:在mybatis中无法通过参数名引用参数
// 正确引用方式: ary0,ary1…
// param1,param2
Book getByMap(Map map);
//3.传入对象:可以在mapper中直接应用对象属性
Book getByBook(Book book);
//4.传入对象:可以在mapper中直接应用对象属性
List listByBookName(String bookName);
//5.区别#{},${}: 模糊查询
// #{}:用参数占位的方式设置数据。不会有注入问题,但是不能用拼接方式拼接sql
//
:
直接用拼接
s
q
l
的方式,拼接数据。有
s
q
l
注入问题。一般用
{}:直接用拼接sql的方式,拼接数据。有sql注入问题。一般用
:直接用拼接sql的方式,拼接数据。有sql注入问题。一般用{value}引用单个参数值
项目实现思路(参考):
代码整体布局:
注意:
完整代码:
数据库/数据表:
create table tb_book
(
book_id int primary key auto_increment,
book_name varchar(20),
author varchar(20),
price decimal(5,1),
publisher varchar(20),
pub_date date
);
select * from tb_book;
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis_0815_KTLX</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--引入jar包-->
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mysql驱动类 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
db.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/70813_db?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123456
mybatis_config.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>
<properties resource="db.properties"></properties>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.yzh7.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--定义关联的mapper接口,通过三一致的规则自动与mapper文件关联-->
<mapper class="com.yzh7.mapper.BookMapper"/>
</mappers>
</configuration>
参考官网:mybatis映射器mappers
https://mybatis.org/mybatis-3/zh/configuration.html#mappers
Book:
package com.yzh7.entity;
import lombok.Data;
import java.util.Date;
@Data
public class Book {
// book_id,book_name,author,price,publisher,pub_date
private Integer bookId;
private String bookName;
private String author;
private Double price;
private String publisher;
private Date pubDate;
}
BookMapper:
package com.yzh7.mapper;
import com.yzh7.entity.Book;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface BookMapper {
List<Map> listAll();
List<Book> listAll2();
Book getById(Integer bookId);
int insert(Book book);
int update(Book book);
int delete(Integer bookId);
Book getByNameAndAuthor(@Param("bn") String bookName,@Param("at") String author);
Book getByMap(Map map);
Book getByBook(Book book);
List<Book> listByBookName(String bookName);
}
BookMapper.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.yzh7.mapper.BookMapper">
<!-- book_id,book_name,author,price,publisher,pub_date-->
<select id="listAll" resultType="map">
select * from tb_book
</select>
<select id="listAll2" resultType="book">
select * from tb_book
</select>
<select id="getById" parameterType="int" resultType="book">
select * from tb_book
where book_id=#{bookId}
</select>
<insert id="insert" parameterType="book">
insert into tb_book
(book_name,author,price,publisher,pub_date)
values
(#{bookName},#{author},#{price},#{publisher},#{pubDate}) <!-- # -->
</insert>
<update id="update" parameterType="book">
update tb_book
set book_name=#{bookName},author=#{author},price=#{price},publisher=#{publisher},pub_date=#{pubDate}
where book_id=#{bookId}
</update>
<delete id="delete" parameterType="int">
delete from tb_book
where book_id=#{bookId}
</delete>
<select id="getByNameAndAuthor" resultType="book">
select * from tb_book
where book_name=#{bn} and author=#{at}
</select>
<select id="getByMap" parameterType="map" resultType="book">
select * from tb_book
where book_name=#{bookName} and author=#{author}
</select>
<select id="getByBook" parameterType="book" resultType="book">
select * from tb_book
where book_name=#{bookName} and author=#{author}
</select>
<select id="listByBookName" resultType="book">
select * from tb_book
where book_name like '%${value}%'
</select>
</mapper>
demo2 :
package com.yzh7.test;
import com.yzh7.entity.Book;
import com.yzh7.mapper.BookMapper;
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 org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class demo2 {
@Test
public void TestGetById(){
BookMapper bookMapper=session.getMapper(BookMapper.class);
Book book=bookMapper.getById(2);
System.out.println("book1:"+book);
}
@Test
public void testGetByNameAndAuthor(){
BookMapper bookMapper=session.getMapper(BookMapper.class);
Book book=bookMapper.getByNameAndAuthor("图书2","作者2");
System.out.println("book2:"+book);
}
@Test
public void testGetByMap(){
BookMapper bookMapper=session.getMapper(BookMapper.class);
Map map=new HashMap();
map.put("bookName","图书2");
map.put("author","作者2");
Book book=bookMapper.getByMap(map);
System.out.println("book3:"+book);
}
@Test
public void testGetByBook(){
BookMapper bookMapper=session.getMapper(BookMapper.class);
Book b=new Book();
b.setBookName("图书2");
b.setAuthor("作者2");
Book book=bookMapper.getByBook(b);
System.out.println("book4:"+book);
}
@Test
public void testListByBookName(){
BookMapper bookMapper=session.getMapper(BookMapper.class);
List<Book> book=bookMapper.listByBookName("图");
System.out.println("book5:"+book);
}
private static SqlSessionFactory factory; //静态
private SqlSession session;
@BeforeClass
public static void befCla() throws IOException {
String resource = "mybatis_config.xml"; //mybatis_config.xml
InputStream inputStream = Resources.getResourceAsStream(resource);
factory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Before
public void bf(){
session=factory.openSession();
}
@After
public void af(){
session.commit();
session.close();
}
}
// A code block
var foo = 'bar';
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118055.html