CREATE table blog(
id VARCHAR(50) not NULL COMMENT '博客id',
title VARCHAR(199) not null COMMENT '博客标题',
author varchar(30) not null COMMENT '博客作者',
createTime datetime not NULL COMMENT '创建时间',
views int(30) not null COMMENT '浏览量'
) ENGINE=INNODB DEFAULT CHARSET=utf8
SHOW tables;
SELECT * from blog;
use mybatis;
CREATE table teacher(
id int(10) not NULL,
`name` varchar(30) DEFAULT NULL,
PRIMARY key(id)
)ENGINE=INNODB DEFAULT charset=utf8;
insert into teacher(id,name) values(1,'秦老师');
CREATE table student(
id int(10) not NULL,
`name` VARCHAR(30) DEFAULT NULL,
tid int(10) DEFAULT NULL,
PRIMARY key(id),
KEY fktid (tid),
CONSTRAINT fktid FOREIGN key(tid) REFERENCES teacher (id)
)ENGINE=INNODB DEFAULT charset=utf8;
insert into student(id,name,tid) values
(1,'小明',1),
(2,'小王',1),
(3,'小李',1),
(4,'小廖',1),
(5,'小周',1)
父模块下prom.xml导入jar包,通过继承后面创建的子项目都拥有这些jar包
父porm.xml和子porm.xml要点示例
//父porm.xml有子模块的架构
mybatis-01
mybatis-03
mybatis-04
mybatis-1more
mybatis-project
//子porm.xml有父模块的标记
Mybatis-Study
org.example
1.0-SNAPSHOT
//解决资源文件无法被导出到target
src/main/resources
**/*.properties
**/*.xml
true
src/main/java
**/*.properties
**/*.xml
true
注意:此处配置顺序有规定!
//读取数据库属性配置文件db.properties
//设置日志和数据表字段与实体类的驼峰和下划线互转的配置
//属性配置之别名优化
//配置运行的环境
//Mapper接口对应的xml文件必须要在此处注册,有三种写法
//我们通常使用class,但前提是Mapper接口和对应的xml文件在一个包下,且名字一样
package com.huang.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
public static SqlSessionFactory sqlSessionFactory;
static {
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis.config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//此处设置布尔值true,增删改就无需sqlSession.commit()提交事务了
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/${需要连接的数据库名如:mybatis}?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=${数据库用户名}
password=${数据库密码}
package com.huang.dao;
import com.huang.pojo.Student;
import java.util.List;
public interface StudentMapper {
// 多对一(学生对老师)的处理---按照查询嵌套处理
List getStudent();
// 多对一(学生对老师)的处理---按照查询嵌套处理
List getStudent2();
}
Mapper接口对应的xml文件示例
//namespace为相对路径下的Mapper接口
//此处编写sql语句,示例
1.安装lombok插件
2.在子porm.xml中配置依赖
org.projectlombok
lombok
1.18.10
3.使用注解@Data即可,见实体类使用
完成了以上环境搭建,我们可以开始测试了
// 测试环境搭建成功
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
List teacherList = mapper.getTeacher();
for (Teacher teacher : teacherList) {
System.out.println(teacher);
}
sqlSession.close();
}
实体类pojo
package com.huang.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
package com.huang.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
// 外键关联的老师对象
private Teacher teacher;
}
1.按照查询嵌套处理
//注意一下固定写法
// #{tid}中tid可以为任何内容
2.按照结果嵌套处理
实体类pojo
package com.huang.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
private List students;
}
package com.huang.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
1.按照查询嵌套处理
// #{id}中id可以为任何内容
2.按照结果嵌套处理
UPDATE mybatis.student
//set会自动添加或者删除,保证sql语句的合法性
name=#{name},
tid=#{tid},
where id = #{id}
//1.接口
List getUserListByLimit(Map map);
//2.mapper.xml配置
//配合使用结果集映射,解决字段名不一致的问题
//3.测试类
@Test
public void testLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
Logger logger = Logger.getLogger(UserDaoTest.class);
logger.info("info:用分页来查询数据");
HashMap map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List userList = userdao.getUserListByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
//1.接口
List getUserListByRowBounds();
//2.mapper.xml配置
//配合使用结果集映射
//3.测试类
@Test
public void testRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
// RowBounds实现
RowBounds rowBounds = new RowBounds(0, 1);
logger.info("info:使用RowBounds来进行分页");
// Java代码层面实现分页 这里是sqlSession执行sql语言的第二种方式,(不推荐)
List userList = sqlSession.selectList("com.huang.dao.UserDao.getUserListByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
//Mapper接口
List getUserListByNameLike(String name);
//模糊查询
//测试类
@Test
public void testLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
//测试模糊查询
//方式一:List userList = userDao.getUserListByNameLike("%王%");
List userList = userDao.getUserListByNameLike("王");
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
//Mapper接口
List getUserListById2(Map map);
//使用map可以自定义参数名
//测试类
@Test
public void test0(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
HashMap map = new HashMap();
map.put("selfDefinedField",5);
List userList = userDao.getUserListById2(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
//增加一个用户 注解适用于简单的业务逻辑
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
int insertUser(User user);
log4j
log4j
1.2.17
# priority :debug> Method: %l ]%n%p:%m%n
#debug log
log4j.logger.debug=debug
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.debug.File=./src/log/debug.log
log4j.appender.debug.Append=true
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#warn log
log4j.logger.warn=warn
log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.warn.File=./src/log/warn.log
log4j.appender.warn.Append=true
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.layout=org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#error
log4j.logger.error=error
log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.error.File = ./src/log/error.log
log4j.appender.error.Append = true
log4j.appender.error.Threshold = ERROR
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
//解决驼峰转数据库中的_
static Logger logger = Logger.getLogger(类对象【Student.class】)
logger.info("info:进入了信息输出");
logger.debug("debug:进入了debug阶段");
logger.error("error:进入了error阶段");
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userdao = sqlSession.getMapper(UserDao.class);
List userlist = userdao.getUserListById(1);
logger.info("info:进入了信息输出");
for (User user : userlist) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test2(){
logger.info("info:进入了信息输出");
}