mybatis整理1

中文文档链接:mybatis中文网

mybatis项目

环境搭建

导入三个依赖
mysql驱动、mybatis、junit

<dependencies>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
	</dependency>
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
	</dependency>
	<dependency>
		<groupId>junit</groupid>
		<artifactId>junit</artifactId>
		<version>4.12</version>
	</dependency>
</dependencies>

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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>//com.mysql.jdbc.Driver
        <property name="url" value="${url}"/>//jdbc:mysql://localhost:3306/mybatis?userSSL=true
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

工具类

private static SqlSessionFactory ssf;
static{try{
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
ssf = new SqlSessionFactoryBuilder().build(is);
}catch(IOException e){
e.printStackTrace();
}}
static SqlSession getSqlSession(){
	SqlSession ss = ssf.openSession();
	return ss;
}

代码

当表中的字段太多,而我们只需要修改某些字段或添加某些字段,其余的不管,可以把传入的参数从对象改为map,只在map中放入你所需要的键值。map传递参数,直接在sql中取key,对象传递参数,直接在sql中取属性,只有一个基本数据类型时可以省略

实体类

mapper.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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

namespace的值等于绑定一个对应的Dao/mapper接口,全限定名
sql中的id等于接口的方法名

增删改需要提交事务

dao接口(mapper)

service

controller

测试

通过sqlSession.getMapper(xxx.class)得到mapper/dao对象

资源导出失败,the error may exist in xxxxxxx

maven由于约定大于配置,配置文件无法被导出或生效,解决方案:
在build中配置resources,防止我们资源导出失败的问题

<build>
	<resources>
		<resource>
			<directory>src/main/resources</directory>
			<includes>
				<include>**/*.xml</include>
			</includes>
			<filtering>true</filtering>
		</resource>
	</resources>
</build>

模糊查询

1、Java代码执行的时候,传递通配符%%
2、在sql拼接中使用通配符,eg:select * from user where name like “%”#{name}“%”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值