只是学习示例,没有整合springboot。
<?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="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/yjw/dao/UserMapper.xml"/>
</mappers>
</configuration>
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try{
String resouce = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resouce);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
<?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="com.yjw.dao.UserDao">
<!--查找全部资料-->
<select id="getUserList" resultType="com.yjw.pojo.User">
select * from mybatis.user
</select>
<insert id="insertUser" parameterType="com.yjw.pojo.User">
insert into mybatis.user (id, name, pwd) VALUES (#{id},#{name},#{pwd});
</insert>
</mapper>
写mapper.xml文件最好放在resource目录下,否则maven导出文件的时候导不出未放在resource目录下的配置文件,切记。
public interface UserDao {
List<User> getUserList();
void insertUser(User user);
}
public class UserDaoTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
}finally {
sqlSession.close();
}
}
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.insertUser(new User(5,"也一样","123"));
sqlSession.commit();
sqlSession.close();
}
}
这时你就可以测试了。
环境配置(environments)
MyBatis可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境。学会使用配置多套运行环境!
Mybatis默认的事务管理器就是JDBC,连接池: POOLED3、属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties元素的子元素来传递。[ db.properties]
对象生命周期和依赖注入框架
依赖注入框架可以代建线程安全的、基于事务的Slsession 和映射器,并将它们直接注入到你的bean中,因此可以直接忽略它们的生命周期。如果对如何通过依赖注入框架来使用 Myeais感兴趣,可以研究一下 MyBatis Spring或MyBatis Guice两个子项目。
SqlSessionFactoryBuilder
这个类可以被实例化、使用和丢弃,-旦创建了SqlSessionFactory, 就不再需要它了。因此SqlSessionFactoryBuilder实例的最佳作用域是方法作用域(也就是局部方法变量)。你可以重用
SqlSessionFactoryBuilder来创建多个SqlSessionFactory实例,但是最好还是不要让其一-直存在, 以保证所有的XML解析资源可以被释放给更重要的事情。
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("userid",2);
map.put("password","123456");
mapper.finduser2(map);
sqlSession.commit();
sqlSession.close();
}
dao层
List<User> getUserListByLike(String like);
mapper
<!-- 模糊查询-->
<select id="getUserListByLike" resultType="com.pojo.User">
select * from mybatis.user where name like #{like} ;
</select>
测试
@Test
public void getUserListByLike(){
获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userListByLike = mapper.getUserListByLike("%w%");
for (User user : userListByLike) {
System.out.println(user);
}
sqlSession.close();
}
MyBatis 可以配置成适应多种环境,不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
可以设置多套运行环境,但只能同时使用一套。Mybatis默认的事务管理是JDBC(当然不止一种事务管理),连接池:POOLED。
driver=com. mysq1. jdbc. Driver
ur1=jdbc:mysq1://localhost: 3306/mybatis?
usessL=true&useunicode=true&characterEncoding=3
username=root
password=123456
在mybatis.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核心配置文件 -->
<configuration>
<!-- 引入外部(db.properties)配置文件-->
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在mybatis-config.xml核心配置文件中注册-->
<mappers>
<mapper resource="com/Dao/UserMapper.xml"/>
</mappers>
</configuration>
在mybatis.xml中写入
方法一:使用于实体类少的情况。目的,编写接口xml的sql语句时,type写的简单-->
<typeAliases>
<typeAlias type="com.pojo.User" alias="user"/>
</typeAliases>
方法二:使用时写小写类名就OK
<typeAliases>
<package name="com.pojo.User"/>
</typeAliases>
如果在pojo类上加入注解" @Alias("hellow"),就只能使用hellow
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<?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="com.it.Dao.UserMapper">
<!-- id名字 type为要映射的类的名字-->
<resultMap id="UserMap" type="User">
<!-- column对应数据库表中的列的名字,
property对应类的属性名字。-->
<result column="pwd" property="password"/>
<result column="id" property="id"/>
<result column="name" property="name"/>
</resultMap>
<!--添加一个resultMap标签-->
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
</mapper>
在mybatis.xml中注意顺序
<!-- 引入外部(db.properties)配置文件-->
<properties resource="db.properties"/>
<!-- 使用标准的默认的日志工厂-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 起别名方法一:使用于实体类少的情况-->
<typeAliases>
<typeAlias type="com.it.pojo.User" alias="user"/>
</typeAliases>
导依赖不用多说
创建log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
<!-- 引入外部(db.properties)配置文件-->
<properties resource="db.properties"/>
<!-- 使用STDOUT_LOGGING标准的默认的日志工厂
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
-->
<!-- 使用log4j日志工厂-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 起别名方法一:使用于实体类少的情况-->
<typeAliases>
<typeAlias type="com.it.pojo.User" alias="user"/>
</typeAliases>
public class UserTest {
static Logger logger = Logger.getLogger(UserDaoTest.class);
@Test
public void testLog4j(){
//日志级别
logger.info("info进入了:testLog4j");
logger.debug("debug进入了:testLog4j");
logger.error("error进入了:testLog4j");
}
}
//dao层
List<User> getUserByLimit(Map<String,Integer> map);
<mapper namespace="com.Dao.UserMapper">
<resultMap id="UserMap" type="User">
<result column="pwd" property="password"/>
<result column="id" property="id"/>
<result column="name" property="name"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
<!-- 分页; 使用参数为Map时,parameterType一定要写,Map的别名是'map',int的别名是 '_int'-->
<select id="getUserByLimit" resultMap="UserMap" parameterType="map">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",1);
map.put("pageSize",3);
List<User> userList = userMapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
在MybatisUtils.java中使用自动提交事务。只能适用于简单的sql,不能多表联查
public static SqlSession getSqlSession() {
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
// 设置增删改查自动提交事务,true。
return sqlSessionFactory.openSession(true);
}
在mybatis,xml中
<mappers>
<mapper class="com.it.Dao.UserMapper"/>
</mappers>
public interface UserMapper {
// 查询全部用户
@Select("select * from user")
List<User> getUserList();
// 存在多个参数
@Select("select * from user where id = #{id} and pwd = #{pwd}")
User getUserByIdPwd(@Param("id")int id,@Param("pwd") String pwd);
// 增:返回值类型只能用int不能用User,否则会报错org.apache.ibatis.binding.BindingException: Mapper method 'com.it.Dao.UserMapper.addUser' has an unsupported return type: class com.it.pojo.User
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);
// 改 @Param,只要有基本类型参数,有几个参数就写几个@Param。
@Update("update user set name=#{name} where id=#{id}")
int updateUser(@Param("name") String name,@Param("id") int id);
// 删
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
}
@Test
public void getUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
sqlSession.close();
}
@Test
public void getUserByIdPwd(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userByIdPwd = mapper.getUserByIdPwd(1,"111");
System.out.println(userByIdPwd);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(7,"c5","253"));
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser("qqq",1);
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(7);
sqlSession.close();
}
CREATE TABLE `student` (
`id` int(10) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`tid` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ftkid` (`tid`),
CONSTRAINT `ftkid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `teacher` (
`id` int(10) NOT NULL,
`name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<?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">
<!--namespace 绑定一对应的Dao/Mapper接口 -->
<!--namespace中的名要和UserMapper.xml的接口一致-->
<mapper namespace="com.it.Dao.StudentMapper">
<!-- 1.查出学生信息 2.通过学生的tid查询到老师的信息-->
<!-- 第一个id为方法名-->
<select id="getStudent" resultMap="student→teacher">
select * from student
</select>
<!-- id为select的resultMap的值,type是映射的类是名字-Student,,相当于select和resulMap连接了起来-->
<resultMap id="student→teacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!-- 在Student.java中第三个变量类型是Teacher类型,是复杂类型,处理:将result换成,
若是对象:association,若是集合:collection
property对应javaType,column对应select
javaType:给property一个类型
select:表明colum要干什么,要select="getTeacher"
select:接着连接下一个id="getTeacher"-->
<association property="tid" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<!--此时TeacherMapper接口没方法,那就设一个getTeacher方法-->
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
</mapper>
<!--方法二:直接写出完整sql。
然后写出resultMap,此时第三个属性仍是复杂类型。
在association只写property对应javaType="Teacher"
然后我们查询老师的id和name,然后在association里面再编写Teacher的property和columu-->
<select id="getStudent2" resultMap="student→teacher2">
select s.id sid,s.name,sname,t.name tname,t.id tid from student s,teacher t where s.tid = t.id
</select>
<resultMap id="student→teacher2" type="Student">
<!-- 注意:查询的就是一个表。此处的column(数据库中的列),就变成了s.id的别名sid等-->
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="tid" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
<?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">
<!--namespace 绑定一对应的Dao/Mapper接口 -->
<!--namespace中的名要和UserMapper.xml的接口一致-->
<mapper namespace="com.it.Dao.TeacherMapper">
<select id="getTeacher" resultMap="teacher→student">
select s.name sname,s.id sid,t.name tname,t.id tid from teacher t,student s where s.tid = t.id and t.id = #{id}
</select>
<resultMap id="teacher→student" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!-- 集合中泛型,使用ofType获取。如果的对象的时候用javaType给定类型-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="sid"/>
</collection>
</resultMap>
</mapper>
public class IDUtils {
public static String getID(){
return UUID.randomUUID().toString().replaceAll("-","...");
}
@Test
public void test(){
System.out.println(IDUtils.getID());
}
}
public interface BlogMapper {
// 插入语句
int insertBlog(Blog blog);
// Where-IF语句,查询blog。动态的根据插入的不同参数,进行不同的查询
List<Blog> queryBlogIF(Map map);
// Where-choose-when-otherwise语句,查询blog。类似switch语句
List<Blog> queryBlogChoose(Map map);
// set-if语句更新blog
int updateBlog(Map map);
}
<?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">
<!--namespace 绑定一对应的Dao/Mapper接口 -->
<!--namespace中的名要和UserMapper.xml的接口一致-->
<mapper namespace="com.it.Dao.BlogMapper">
<!--插入数据-->
<insert id="insertBlog" parameterType="blog">
insert into mybatis.blog(id,title,author,create_time,views) values (#{id},#{title},#{author},#{createTime},#{views})
</insert>
<!--Where-IF语句。有了where标签,当只满足title时,语句前面的and会被忽略-->
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="id != null">
--如果id !=null,就追加一个and id=#{id}
id = #{id}
</if>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
<if test="create_time != null">
and create_time = #{create_time}
</if>
<if test="views != null">
and views = #{views}
</if>
</where>
</select>
<!--Where-choose-when-otherwise语句。当传入的参数都不在when中存在时,就执行otherwise-->
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="id != null">id = #{id}</when>
<when test="title != null">and title = #{title}</when>
<when test="author != null">and author = #{author}</when>
<when test="create_time != null">and create_time = #{create_time}</when>
<when test="views != null">and views = #{views}</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
</select>
<!--set-if语句更新Blog-->
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">title = #{title},</if>
<if test="author != null">author = #{author},</if>
<if test="create_time != null">create_time = #{create_time},</if>
<if test="views != null">views = #{views}</if>
</set>
where id = #{id}
</update>
</mapper>
public class MyTest {
@Test //插入语句
public void insert(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtils.getID());
blog.setTitle("Mybatis so easy");
blog.setAuthor("Mr.1");
blog.setCreateTime(new Date());
blog.setViews(999);
mapper.insertBlog(blog);
blog.setId(IDUtils.getID());
blog.setTitle("Spring so easy");
mapper.insertBlog(blog);
blog.setId(IDUtils.getID());
blog.setTitle("Math so easy");
mapper.insertBlog(blog);
blog.setId(IDUtils.getID());
blog.setTitle("Mysql so easy");
mapper.insertBlog(blog);
sqlSession.close();
}
@Test//Where-IF语句,查询blog。动态的根据插入的不同参数,进行不同的查询。可以同时满足多个条件
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title","Mybatis so easy");
map.put("views","888");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
@Test//Where-choose-when-otherwise语句,查询blog。类似switch语句。只能满足最先的那个条件。
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title","Mybatis so easy");
mapper.queryBlogChoose(map);
System.out.println(map);
sqlSession.close();
}
@Test// set-if语句更新Blog
public void updateBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("id","92036d82.bd3b.4a78.b602.9d3c5ec71a46");
map.put("views",777);
mapper.updateBlog(map);
sqlSession.close();
}
}
<!--将每次都要编写的IF语句提取出来,id随便取-->
<sql id = "sql-if">
<if test="title != null">title = #{title},</if>
<if test="author != null">author = #{author},</if>
<if test="create_time != null">create_time = #{create_time},</if>
<if test="views != null">views = #{views}</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<!--引用提取出来的SQL片段SQL-->
<include refid="sql-if"/>
</where>
</select>
<!--查询where 1=1 and (id=0 or id=2 or id=3)用foreach-->
<select id="queryBlogForEach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--类似集合的foreach循环。foreach标签内容分别为:给定一个集合的名字,将取出的内容给定一个名字,开始是的样子and (,结尾的样子),分开分隔是or。id和#{id}对应-->
<foreach clloection="list" item="id" open="and (" close=")" separator="or"> id = #{id} </foreach>
</where>
//通过id查询。将List集合存到Map里面,List里面都是id
Map map = new HashMap();
List<Integer> list = new ArraryList<Integer>();
list.add(1);
map.put(list);
mapper.queryBlogForEach(map);