您好,登录后才能下订单哦!
这篇文章主要介绍了Mybatis中实体类别名、多参数、动态SQL的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
开始讲实体类别名、多参数、动态SQL等
DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `salary` decimal(10, 2) NOT NULL, `age` int(11) NULL DEFAULT NULL, `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `job` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 43 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of test -- ---------------------------- INSERT INTO `test` VALUES (1, '小明', 40000.00, 18, '北京', '程序猿'); INSERT INTO `test` VALUES (2, '小强', 50000.00, 19, '南京', '程序汪'); INSERT INTO `test` VALUES (3, '小月月', 50000.00, 20, '天津', '程序狗'); INSERT INTO `test` VALUES (4, '小月鸟', 40000.00, 21, '广州', '程序屌丝');
package entity; import java.math.BigDecimal; /** * @author 发现更多精彩 关注公众号:木子的昼夜编程 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作 * @create 2021-08-25 22:05 */ public class TestEntity { private Long id; private String name; private BigDecimal salary; private Integer age; private String city; private String job; // get set方法省略 IntelliJ IDEA 生成快捷键是Alt+Inert 选择Getter and Setter // toString 方法省略 IntelliJ IDEA 生成快捷键是Alt+Inert 选择 toString }
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> <!--这里一定注意顺序 --> <typeAliases> <typeAlias type="entity.TestEntity" alias="testEntity"/> </typeAliases> <!--省略environments 看前2篇 --> <!--省略扫描 看前2篇--> </configuration>
配置文件顺序要这样配置:
<properties>...</properties> <settings>...</settings> <typeAliases>...</typeAliases> <typeHandlers>...</typeHandlers> <objectFactory>...</objectFactory> <objectWrapperFactory>...</objectWrapperFactory> <plugins>...</plugins> <environments>...</environments> <databaseIdProvider>...</databaseIdProvider> <mappers>...</mappers>
<!--根据主键查询--> <select id="get" resultType="testEntity"> select * from test where id = #{id} </select>
public class TestMain { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); System.out.println(mapper); // 查询数据 TestEntity testEntity = mapper.get(1L); System.out.println(testEntity); } } }
扫描包路径 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> <!--扫描包路径--> <typeAliases> <package name="entity"/> </typeAliases> <!--省略environments 看前2篇 --> <!--省略扫描 看前2篇--> </configuration>
用扫描包路径的方式,实体类别名默认就是java类首字母小写
例如:TestEntity --> testEntity
还可以注解指定:
@Alias("testEntityxxoo") public class TestEntity { // 其他省略 }
如果写了注解@Alias 别名就不是”testEntity”了 ,就变成”testEntityxxoo“
映射类型 | |
---|---|
_byte | byte |
_long | long |
_short | short |
_int | int |
_integer | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
integer | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
bigdecimal | BigDecimal |
object | Object |
map | Map |
hashmap | HashMap |
list | List |
arraylist | ArrayList |
collection | Collection |
iterator | Iterator |
<!--增加--> <insert id="save" useGeneratedKeys="true" keyProperty="id"> INSERT INTO `test`( `name`, `salary`) VALUE (#{name}, #{salary}); </insert>
public class TestMain { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); // 测试id是否到了实体类里边 TestEntity testEntity = new TestEntity(); testEntity.setName("小鸭子"); testEntity.setSalary(new BigDecimal(100000)); mapper.save(testEntity); System.out.println("主键:"+testEntity.getId()); } } }
输出结果:
主键不是直接返回的,而是把主键值设置到插入的对象里的
<!--增加--> <insert id="save"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO `test`(`id`, `name`, `salary`) VALUE (#{id},#{name}, #{salary}) </insert>
// 根据主键查询 TestEntity get(Long id);
<!--根据主键查询--> <select id="get" resultType="testEntity"> select * from test where id = #{id} </select> <select id="get" resultType="testEntity"> select * from test where id = #{xx} </select> <select id="get" resultType="testEntity"> select * from test where id = #{oo} </select> <select id="get" resultType="testEntity"> select * from test where id = #{aaabbb} </select>
如果只有一个参数,并且参数类型是Java基础类型或String类型,那么使用这个参数的时候
#{xxoo} xxoo可以是任意字符 与方法输入参数名称无关
上边例子中:id、xx、oo、aaabbb 都可以使用 ,但是哈,我们一般见名知意,传递的什么参数(id),我们xml就用#{传递的参数} 这不是必须但可以遵循这个规范
// 新增 void save(TestEntity testEntity);
<!--增加--> <insert id="save"> INSERT INTO `test`(`name`, `salary`) VALUE (#{name}, #{salary}) </insert>
这个很容易明白,实体类参数叫什么 这里#{}里边就用什么
// 根据名称模糊查询 List<TestEntity> listByNameAndAge(@Param("name") String name,@Param("age") Integer age);
<!--根据名称和年龄查寻--> <select id="listByNameAndAge" resultType="testentity"> select * from test where 1=1 <if test="name != null"> and name like CONCAT('%',#{name},'%') </if> <if test="age != null"> and age = #{age} </if> </select>
public class TestMain { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); List<TestEntity> list = mapper.listByNameAndAge("小强", 19); System.out.println(list); } } }
用Map跟用实体类差不多 就key值当做是实体类的字段名称就可以
// 多参数Map 方式传递 List<TestEntity> listByNameAndAgeMap(Map<String, Object> param);
<!--param多参数map使用--> <select id="listByNameAndAgeMap" resultType="testentity"> select * from test where 1=1 <if test="name != null"> and name like CONCAT('%',#{name},'%') </if> <if test="age != null"> and age = #{age} </if> </select>
public class TestMain { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); Map<String,Object> param = new HashMap<>(); param.put("name", "小强"); param.put("age", 19); List<TestEntity> list = mapper.listByNameAndAgeMap(param); System.out.println(list); } } }
默认有两套参数:
arg0、arg1、arg2、argxxx ; arg从0开始按照方法参数顺序
param1、param2、param3、paramxxx ; param从1开始按照方法参数顺序
// 什么都不用 List<TestEntity> listByNameAndAgeNone(String name, int age);
<!--用默认顺序--> <select id="listByNameAndAgeNone" resultType="testentity"> select * from test where 1=1 <if test="arg0 != null"> and name like CONCAT('%',#{arg0},'%') </if> <if test="arg1 != null"> and age = #{arg1} </if> </select>
<!--用默认顺序--> <select id="listByNameAndAgeNone" resultType="testentity"> select * from test where 1=1 <if test="param1 != null"> and name like CONCAT('%',#{param1},'%') </if> <if test="param2 != null"> and age = #{param2} </if> </select>
public class TestMain { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); List<TestEntity> list = mapper.listByNameAndAgeNone("小月", 20); System.out.println(list); } } }
注意传递数组的话,默认参数名称为arry
// 根据年龄集合查询 List<TestEntity> listByAges(int[] ages);
<select id="listByAges" resultType="testentity"> select * from test where 1=1 <if test="array != null and array.length >0"> and age in <foreach collection="array" item="age" open="(" separator="," close=")"> #{age} </foreach> </if> </select>
public class TestMain { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); int[] ages = new int[]{19,20}; List<TestEntity> list = mapper.listByAges(ages); System.out.println(list); } } }
例如:名称是小强并且年龄是19 或者名称是小月月年龄是20 的数据
// 根据多组参数查询 List<TestEntity> listByNameAndAges(TestEntity[] params);
<select id="listByNameAndAges" resultType="testentity"> select * from test where 1=1 <if test="array != null and array.length >0"> and ( <foreach collection="array" item="item" separator="or" > (name = #{item.name} and age = #{item.age}) </foreach> ) </if> </select>
public class TestMain { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper TestMapper mapper = session.getMapper(TestMapper.class); TestEntity[] params = new TestEntity[2]; TestEntity testEntity01 = new TestEntity(); testEntity01.setName("小强"); testEntity01.setAge(19); TestEntity testEntity02 = new TestEntity(); testEntity02.setName("小月月"); testEntity02.setAge(20); params[0] = testEntity01; params[1] = testEntity02; List<TestEntity> list = mapper.listByNameAndAges(params); System.out.println(list); } } }
最后输出的sql格式是这样的:
select* from test where 1=1 and (
(name = '小强' and age = 19) or
(name = '小月月' and age = 20)
)
集合与数组差不多,但还是有点儿差别
不同点1: 集合如果不指定参数名称的话默认使用:collection或者list 不是array
不同点2:集合判断大小是这样的 用的size() 不是length
<if test="list != null and list.size() >0"></if>
select是Mybatis使用最多的标签之一,他与insert update delete不同,他不对数据库值做改变,只是查
insert、 update、 delete 会对数据库的值做变更,这三个标签可以混用,也就是说他们功能一样,出三个的意义就是为了业务上可以区分一下是新增、修改还是删除。一般我们也遵循这个使用。
感谢你能够认真阅读完这篇文章,希望小编分享的“Mybatis中实体类别名、多参数、动态SQL的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。