MyBatis学习路上打的那些码(四、查询多个User和一个优化typeAlias)

来源:互联网 发布:网络兼职平台 编辑:程序博客网 时间:2024/05/22 08:07

1,查询多个User

先加一个select,注意resultType用的是UserPo,当返回值不止一行的时候,我们只要把每行的类型告诉mybatis就好了

<select id="getAllUser" resultType="com.demo.user.po.UserPo">select * from user</select>
然后就可以用了,注意,接受的时候,就不能用UserPo了,要用List了。

//查询所有@Testpublic void test5() {List<UserPo> users=ss.selectList("getAllUser");for(UserPo user:users) {System.out.println(user);}}
完事~


2,一个优化typeAlias

如果你是处女座,那么你可能已经发现我们的代码里有个很让人不得劲儿的地方了,没错,就是这个地方:

annoying

当然可以

其实工程真的做起来,会有各种各样的select,也就会有很多resultType,如果我们每次都写全限定名的话,当然很难受,所以,MyBatis提供了一种方式:typeAlias,就是给可能用到的po起一个别名,用到的时候调用别名就好了~因为工程到处都会用到po,也就是说,很多sql语句都可能用到到po,所以,起别名当然要在大的那个配置文件里了~(我们不希望每个mapper都有一套自己的“别名系统”吧),也就是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="com.demo.user.po.UserPo" alias="user" /><!-- 这里还能放好多typeAlias --></typeAliases><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://localhost:3306/heiheihahadb" /><property name="username" value="root" /><property name="password" value="8888" /></dataSource></environment></environments><mappers><mapper resource="com/demo/user/mapper/user_mapper.xml" /></mappers></configuration>
这样,在mapper那里,就可以直接用别名了:

<select id="getAllUser" resultType="user">select * from user</select>

很简单吧,如果还有其他的别名,只要在typeAliases标签里面再添加别的typeAlias就可以了,像这样:<typeAlias type="com.xxxx.xxxx.xxPo" alias="xx"/>。

还是感觉有点麻烦,有没有一种方法,用一行代码,把po包下的所有po都起好别名呢?

也有~

<typeAliases><package name="com.demo.user.po"/></typeAliases>
不用一个一个写typeAlias了,把po所在的包写在这里,就可以直接通过类名使用了:

<select id="getAllUser" resultType="UserPo">select * from user</select>

完事。





阅读全文
0 0
原创粉丝点击