Mybatis系列文章(2)
一.基本语法操作
1.模糊查询
sql语句:
select * from user where username like username
在IUserDao.xml中的语句:
<select id="findbyName" parameterType="java.lang.String" resultType="com.itheima.domain.User">
select * from user where username like #{username}
</select>
2.聚合函数
SQL语句:
select count(*/字段名) from 数据表
在IUserDao.xml中的语句:
<select id="count" resultType="java.lang.Integer" >
select count(id) from user
</select>
3.配置插入语句操作后,获取插入数据的id
在IUserDao.xml中的语句:
4.resultType的说明
在windows操作系统中,mysql不区分大小写
我们一般是让表中的列名与java中实例的属性名保持一致,就可以保证一一对应
但要是不一致的情况,则会出现各种错误,如何解决呢?
如果改为这样的情况,使他们不一样
a》采用起别名的方式,在sql语句上实现名称统一
b》在mybatis层面用映射解决问题:
<resultMap id="userMap" type="com.itheima.domain.User">
<!-- 主键需要单独定义-->
<id property="Userid" column="id"></id>
<!-- 其他列-->
<result property="Username" column="username"></result>
<result property="Userbirthday" column="birthday"></result>
<result property="Usersex" column="sex"></result>
<result property="Useraddress" column="address"></result>
</resultMap>
5.URL
配置连接数据库的信息
resource 属性:用于指定 properties 配置文件的位置,要求配置文件必须在类路径下
resource=“jdbcConfig.properties”
url 属性:
URL: Uniform Resource Locator 统一资源定位符
http://localhost:8080/mystroe/CategoryServlet URL
协议 主机 端口 URI
URI:Uniform Resource Identifier 统一资源标识符
/mystroe/CategoryServlet
它是可以在 web 应用中唯一定位一个资源的路径
比如说在文件中的用
resource可以指定的资源,用url也可以
file:///D:/IDEA%E9%A1%B9%E7%9B%AE/Mybatis-1/src/main/resources/SqlMapConfig.xml
但必须是英文路径,不然容易乱码
6.标签 typeAliases
<typeAliases>
<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>
</typeAliases>
这样一来,就给了实体类一个别名,在xml文件中就可以使用这个别名了
另外,像string,int这些都有别名,直接使用就可以了,也可以用java.lang.integer
当需要别名的类太多了时候,就可以给包中的所有类都给别名,而且别名就位实体类名
比如
<typeAliases>
<package name="com.itheima.domain"/>
</typeAliases>
效果一样
在这里也可以使用
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<mapper resource="com/itheima/dao/IUserDao.xml"/>
</mappers>