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
			
			true
		
	

模糊查询

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

你可能感兴趣的:(java)