mac 安装mysql
brew install mysql
mysql.server start
mysql_secure_installation
数据库复习
CREATE DATABASE mybatis
use mybatis
;
create table user
(id
int(20) not null PRIMARY key,name
VARCHAR(30) DEFAULT null,pwd
VARCHAR(30) DEFAULT null
)ENGINE=INNODB DEFAULT charset=utf8;
insert into user
VALUES(2,’bbbb’,’1234’)
官方文档:mybatis配置
坑
1. Resource爆红,是直接粘贴过来导致没有自动导入包,删除后手动敲一遍即可
2. 提升作用域
1. 配置
1.1、配置pom
<?xml version=”1.0” encoding=”UTF-8”?>
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>org.example</groupId><br /> <artifactId>Mybatis_Study</artifactId><br /> <packaging>pom</packaging><br /> <version>1.0-SNAPSHOT</version><br /> <modules><br /> <module>mybatis-01</module><br /> </modules>
<dependencies><br /> <dependency><br /> <groupId>mysql</groupId><br /> <artifactId>mysql-connector-java</artifactId><br /> <version>8.0.21</version><br /> </dependency><br /> <dependency><br /> <groupId>org.mybatis</groupId><br /> <artifactId>mybatis</artifactId><br /> <version>3.4.5</version><br /> </dependency><br /> <dependency><br /> <groupId>junit</groupId><br /> <artifactId>junit</artifactId><br /> <version>4.12</version><br /> <scope>test</scope><br /> </dependency><br /> </dependencies>
1.2 Resources配置mybatis-config.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">
1.3编写mybatis工具类
package com.haifeng.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;
/*
@Author: haifengzuishuai
@Data: 2021/6/13 8:33 下午
/
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = “mybatis-config.xml”;
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}<br /> public static SqlSession getSqlSession(){<br /> return sqlSessionFactory.openSession();<br /> }<br />}
编写代码
- package com.haifeng.pojo;
/*
@Author: haifengzuishuai
@Data: 2021/6/14 12:13 上午
/
//实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {<br /> return id;<br /> }
public void setId(int id) {<br /> this.id = id;<br /> }
public String getName() {<br /> return name;<br /> }
public void setName(String name) {<br /> this.name = name;<br /> }
public String getPwd() {<br /> return pwd;<br /> }
public void setPwd(String pwd) {<br /> this.pwd = pwd;<br /> }
@Override<br /> public String toString() {<br /> return "User{" +<br /> "id=" + id +<br /> ", name='" + name + '\'' +<br /> ", pwd='" + pwd + '\'' +<br /> '}';<br /> }<br />}
- 实现dao接口
package com.haifeng.dao;
import com.haifeng.pojo.User;
import java.util.List;
/*
@Author: haifengzuishuai
@Data: 2021/6/14 12:25 上午
/
public interface UserDao {
List
}
3. 接口实现类由impl转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">
4.测试
注意:
1.1、 org.apache.ibatis.binding.BindingException: Type interface com.haifeng.dao.UserDao is not known to the MapperRegistry.
需要到mybatis-config.xml中注册MapperRegistry
每一个mapper.xml都需要在核心配置文件中注册
1.2 初始化失败需要去mybatis-config 核心文件中去注册
java.lang.ExceptionInInitializerError
1.3 注册后报:
java.lang.ExceptionInInitializerError
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in com/haifeng/mapper/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/haifeng/mapper/UserMapper.xml
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/haifeng/mapper/UserMapper.xml
<br /> Caused by: java.io.IOException: Could not find resource com/haifeng/mapper/UserMapper.xml
maven约定大于配置,写的配置文件无法被导出,pom中添加过滤
1.4
Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
解决:
提示信息表明数据库驱动com.mysql.jdbc.Driver’已经被弃用了、应当使用新的驱动com.mysql.cj.jdbc.Driver’
所以,按照提示更改jdbc.properties配置 .com.mysql.jdbc.Driver 改为 com.mysql.cj.jdbc.Driver
1.5
Access denied for user ‘root’@’localhost’ (using password: YES)
鉴权密码或者账号错误
增删改查CRUD
namespace
select
选择,查询语句
id:对应的namespace方法名
resultType:Sql执行后的返回值
parameterType:传入参数类型
userDao.java
public interface UserDao {
List
User getUserById(int id);
}
userMapper.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">
UserDaoTest.java
@Test
public void getByUserId() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User userList = mapper.getUserById(1);
System.out.println(userList);
sqlSession.close();
}
insert
需要提交事务
Dao.java
public interface UserDao {
List
User getUserById(int id);
int addUser(User user);<br />}
UserMapper.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">
insert into mybatis.user value (#{id},#{name},#{pwd})
test
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int aa = mapper.addUser(new User(3, “海峰最帅”, “520520520”));
sqlSession.commit();//需要提交事务
System.out.println(aa);
sqlSession.close();
}
update
int updataUser(User user);
<update id="updataUser" parameterType="com.haifeng.pojo.User"><br /> update mybatis.user set name = #{name} where id=#{id};<br /> </update><br /> @Test<br /> public void updataUser() {<br /> SqlSession sqlSession = MybatisUtils.getSqlSession();<br /> UserDao mapper = sqlSession.getMapper(UserDao.class);<br /> int aa = mapper.updataUser(new User(1, "aabbcc", "520520520"));<br /> sqlSession.commit();//需要提交事务<br /> System.out.println(aa);<br /> sqlSession.close();<br /> }
delete
int deleteaUser(int id);
delete from mybatis.user where id=#{id}
@Test
public void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int aa = mapper.deleteaUser(2);
sqlSession.commit();//需要提交事务
System.out.println(aa);
sqlSession.close();
}
log4j配置
pom导依赖
<dependency><br /> <groupId>log4j</groupId><br /> <artifactId>log4j</artifactId><br /> <version>1.2.17</version><br /> </dependency>
resources 下的log4j.properties配置
log4j.appender.Console.encoding=UTF-8
#将等级为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/haifeng.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
mybatis-config 配置
<settings><br /> <setting name="logImpl" value="LOG4J"/><br /> </settings>
类中使用
import org.apache.log4j.Logger;
static Logger logger = Logger.getLogger(UserDaoTest.class);
注解开发
@SELECT
package com.haifeng.dao;
import com.haifeng.pojo.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
/*
@Author: haifengzuishuai
@Data: 2021/6/14 12:25 上午
/
public interface UserDao {
List
@Select(“select * from user”)//注解开发
List
User getUserById(int id);
int addUser(User user);
int updataUser(User user);
int deleteaUser(int id);
List<User> getUserByLimit(Map<String, Integer> map);
}
Mybatis-config.xml关联
测试
@Test
public void test1() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
方法存在多个参数
@Select("select * from user where id = #{id}")<br /> User getUserById1(@Param("id") int id);
LomBok 自动生成getset等方法
@Data
@ToString
@AllArgsConstructor
@EqualsAndHashCode
@NoArgsConstructor
动态SQL
- 导包
- 编写配置文件
- 编写实体类
- 编写实体类对应的mapper接口及mapper.xml
三高 高并发 高可用 高性能
读写分离主从复制
1.什么是缓存[Cache ]?。存在内存中的临时数据。
。将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查
询,从缓存中查询,从而提高查询效率,解决了高井发系统的性能问题。
2.为什么使用缓存?
。减少和数据库的交互次数,减少系统开销,提高系统效率。
3.什么样的数据能使用缓存?
。经常查询并且不经常改变的数据。 [可以使用缓存]
后续学习
mapper模板
<?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>
<select id="对应的接口方法" resultType="接口的返回类" parameterType="参数类型">
select * from Blog where id = #{id}
</select>