梅州网站建设公司,视频教学互动网站建设,wordpress安装后查看站点失败,装饰协会网站源码1. 相关文档地址
中文文档 https://mybatis.org/mybatis-3/zh/index.htmlMybatis可以配置成适应多种环境#xff0c;不过每个SqlSessionFactory实例只能选择一种环境。Mybatis默认事务管理器是JDBC#xff0c;连接池#xff1a;POOLEDMaven仓库:下载地址dependency…1. 相关文档地址
中文文档 https://mybatis.org/mybatis-3/zh/index.htmlMybatis可以配置成适应多种环境不过每个SqlSessionFactory实例只能选择一种环境。Mybatis默认事务管理器是JDBC连接池POOLEDMaven仓库:下载地址
dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.2/version/dependencygitHub地址中文文档地址mybatis官方文档文档地址
2. demo
新建普通maven项目作为父项目导入sql驱动mybatisjunit组件 !--导入依赖--dependencies!--mysql驱动--dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion5.1.46/version/dependency!--Mybatis--dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.2/version/dependency!--junit--dependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.12/version/dependency/dependencies新建新组件作为子级项目普通maven的module 添加配置文件 在src-main-resources目录下新建mybatis-config.xml文件把官方的配置代码复制粘贴(不能在配置文件中写中文注释) ?xml version1.0 encodingUTF-8 ?!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtdconfigurationenvironments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLEDproperty namedriver value${driver}///数据库驱动不同驱动可连接不同数据库服务器property nameurl value${url}///连接数据库的目录property nameusername value${username}///数据库名字默认rootproperty namepassword value${password}///数据库密码自己的数据库密码一般为root/dataSource/environment/environments/configuration编写mybatis工具类 //SqlSessionFactory --生产-- SqlSessionpublic class MybatisUtils {private static SqlSessionFactory sqlSessionFactory; //提升作用域//获取工厂固定代码static {try {String resourcemybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}//获取sqlSession//SqlSession完全包含了面向对象数据库执行SQL命令所需的方法public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession();}}实体类 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() {return id;}public void setId(int id) {this.id id;}public String getName() {return name;}public void setName(String name) {this.name name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd pwd;}Overridepublic String toString() {return User{ id id , name name \ , pwd pwd \ };}
}Dao接口 public interface UserDao {ListUser getUserList();}接口实现类改为以xxxMapper.xml的配置文件 注意事项配置文件中不要写中文注释如果非要写解决方法见后面的异常解决方案 ?xml version1.0 encodingutf-8 ?!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd!--namespace命名空间绑定mapper/Dao接口--mapper namespacecom.qian.dao.UserDao!--id:接口的方法resultType接口的返回值类型--select idgetUserList resultTypecom.qian.pojo.Userselect * from mybatis.user where id #{id}/select/mapper测试类 public class UserDaoTest {Testpublic void test(){//获取SqlSession对象SqlSession sqlSession MybatisUtils.getSqlSession();//获取mapperUserDao mapper sqlSession.getMapper(UserDao.class);ListUser list mapper.getUserList();for (User u:list){System.out.println(u);}//不推荐使用/*这种方式能够正常工作对使用旧版本 MyBatis 的用户来说也比较熟悉。但现在有了一种更简洁的方式——使用和指定语句的参数和返回值相匹配的接口比如 BlogMapper.class现在你的代码不仅更清晰更加类型安全还不用担心可能出错的字符串字面值以及强制类型转换。*/// ListUser list sqlSession.selectList(com.qian.dao.UserDao.getUserList);// for (User user : list) {// System.out.println(user);// }//关闭SqlSessionsqlSession.close();}}异常1org.apache.ibatis.binding.BindingException: Type interface com.qian.dao.UserDao is not known to the MapperRegistry. 解决方法每一个Mapper.xml文件都需要在src-main-resources目录下新建mybatis-config.xml的核心配置文件中注册 mappersmapper resourcecom/qian/dao/UserMapper.xml
/mappers异常2 Error building SqlSession. The error may exist in com/qian/dao/UserMapper.xml Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/qian/dao/UserMapper.xml 解决方法 !-- 在maven中约定大于配置在pom中添加此文件可以解决 --
buildresourcesresourcedirectorysrc/main/resources/directoryincludesinclude**/*.properties/includeinclude**/*.xml/include/includesfilteringtrue/filtering/resourceresourcedirectorysrc/main/java/directoryincludesinclude**/*.properties/includeinclude**/*.xml/include/includesfilteringtrue/filtering/resource/resources
/build异常3 Error building SqlSession. The error may exist in com/qian/dao/UserMapper.xml Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 6; 解决方法 ?xml version1.0 encodingUTF-8 ?
!-- 把mybatis-config.xml与mybatis-config.xml文件的encoding修改成下面的 --
?xml version1.0 encodingUTF8 ?异常4 Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 解决方法 useSSLtrue改为false(true也可以需要在mysql中启用SSL property nameurl valuejdbc:mysql://localhost:3306/mybatis?useSSLfalseamp;useUnicodetrueamp;characterEncodingUTF8amp;serverTimezoneGMT%2B8/参考文档 https://www.kuangstudy.com/bbs/1580393245333508097
3.配置文件优先级
如果两个文件有同一个字段优先使用外部配置文件
配置db.propertiesdrivercom.mysql.jdbc.Driverurljdbc:mysql://localhost:3306/mybatis?useSSLfalse;useUnicodetrue;characterEncodingUTF8;serverTimezoneGMT%2B8;autoConnecttrueusernamerootpasswordroot
在核心配置文件中引入
注意在xml中所有的标签都可以规定顺序(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?).核心文件配置configurationproperties resourcedb.properties/environments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/transactionManagerdataSource typePOOLEDproperty namedriver value${driver}/property nameurl value${url}/property nameusername value${username}/property namepassword value${password}//dataSource/environment/configuration
总结可以直接引入外部文件也可以在property/property里面配置外部引入的文件db.properties的优先级要比在property/property要高
错误提示4. LOG4J
Log4j是一个由Java编写可靠、灵活的日志框架是Apache旗下的一个开源项目现如今Log4j已经被移植到了C、C、Python等语言中服务更多的Developer #newhappy log4j.properties startlog4j.rootLoggerDEBUG,console,file#控制台输出 console appenderlog4j.appender.consoleorg.apache.log4j.ConsoleAppenderlog4j.appender.console.TargetSystem.outlog4j.appender.console.thresholdDEBUGlog4j.appender.console.layoutorg.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern[%c]-%m%n#文件输出 rolling file appenderlog4j.appender.fileorg.apache.log4j.RollingFileAppenderlog4j.appender.file.File./log/yu.loglog4j.appender.file.MaxFileSize10mBlog4j.appender.file.MaxBackupIndex2log4j.appender.file.layoutorg.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern%d{mmm d,yyyy hh:mm:ss a} : %p [%t] %m%nlog4j.appender.file.thresholdDEBUG#日志输出级别 loggerlog4j.logger.org.mybatisDEBUGlog4j.logger.java.sqlDEBUGlog4j.logger.java.sql.StatementDEBUGlog4j.logger.java.sql.ResultSetDEBUGlog4j.logger.java.sql.PreparedStatementDEBUG#newhappy log4j.properties end解决方法配置maven导入log4j
pom.xml!-- https://mvnrepository.com/artifact/log4j/log4j --dependencygroupIdlog4j/groupIdartifactIdlog4j/artifactIdversion1.2.17/version/dependency5. MyBatis执行流程 Resource获取加载全局配置文件实例化SqlSessionFactoryBuilder构造器解析配置文件流XMLConfigBuilderConfiguration所有的配置信息SqlSessionFactory实例化transaction事务管理器创建executor执行器创建sqlSession实现CRUD查看是否执行成功提交事务关闭sqlSession连接 注意#{} 和KaTeX parse error: Expected EOF, got # at position 7: {} 注意#̲{} 和{} 1.#{} 解析为一个 JDBC 预编译语句prepared statement的参数标记符一个 #{ } 被解析为一个参数占位符而${}仅仅为一个纯碎的 string 替换在动态 SQL 解析阶段将会进行变量替换。2.#{} 解析之后会将String类型的数据自动加上引号其他数据类型不会而${} 解析之后是什么就是什么他不会当做字符串处理。3#{} 很大程度上可以防止SQL注入SQL注入是发生在编译的过程中因为恶意注入了某些特殊字符最后被编译成了恶意的执行操作而${} 主要用于SQL拼接的时候有很大的SQL注入隐患。4.在某些特殊场合下只能用${}不能用#{}。例如在使用排序时ORDER BY ${id}如果使用#{id}则会被解析成ORDER BY “id”,这显然是一种错误的写法。 6. Lombok
左上角File-Settings-Plugins
搜索Lombok,下载安装
导入mavendependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdversion1.18.10/version/dependencyLombok的支持 Getter and Setter FieldNameConstants ToString EqualsAndHashCode AllArgsConstructor, RequiredArgsConstructor and NoArgsConstructor Log, Log4j, Log4j2, Slf4j, XSlf4j, CommonsLog, JBossLog, Flogger, CustomLog Data Builder SuperBuilder Singular Delegate Value Accessors Wither With SneakyThrows val var experimental var UtilityClass Lombok config system Code inspections Refactoring actions (lombok and delombok) 常用支持 Data支持: 无参构造gettersetter,toString,hashCode,equals AllArgsConstructor: 有参构造 NoArgsConstructor: 无参构造 使用方法在实体类上加注解 配置 关联 association 多对一集合 collection 一对多javaType 指定实体类中属性的类型ofType 用来指定映射到List或者集合中的pojo类型泛型中的约束类型 7.缓存 什么是缓存(Cache) 每次查询都要连接数据库比较耗资源我们把查询到的数据暂存到内存里面下次查询的时候从内存读取 这个地方就叫缓存。 存在内存中的临时数据 将用户经常查询的数据放在缓存内存中用户去查询数据就不用从磁盘上关系型数据库数据文件查询、从缓存中查询从而提高查询效率解决了高并发系统的性能问题 为什么要使用缓存 减少和数据库的交互次数减小系统开销提高系统效率 什么样的数据适用于缓存 经常查询且不经常改变的数据
Mybatis缓存 Mybatis系统默认定义了两级缓存 默认情况下只有一级缓存开启(SqlSession缓存也称为本地缓存) 二级缓存需要手动配置它是基于namespace级别的缓存 Mybatis定义了缓存接口Cache可以通过实现Cache接口来自定义二级缓存 二级缓存
二级缓存也叫全局缓存一级缓存作用域太低了所以诞生了二级缓存基于namespace级别的缓存一个命名空间对应一个二级缓存工作机制 1.一个会话查询一条数据这个数据就会被放在当前会话的一级缓存中 2.如果当前会话关闭了这个会话对应的一级缓存就没了但是我们想要的是会话关闭了一级缓存中的数据被保存到二级缓存中 3.新的会话查询信息就可以从二级缓存中获取内容 4.新的会话查询信息就可以从二级缓存中获取内容 5.不同的mapper查出的数据会放在自己对应的缓存map中也就是说一级缓存死的时候把数据交给了二级缓存
提示缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件在共用接口中的语句将不会被默认缓存。你需要使用 CacheNamespaceRef 注解指定缓存作用域。
这些属性可以通过 cache 元素的属性来修改。比如
cacheevictionFIFOflushInterval60000size512readOnlytrue/这个更高级的配置创建了一个 FIFO 缓存每隔 60 秒刷新最多可以存储结果对象或列表的 512 个引用而且返回的对象被认为是只读的因此对它们进行修改可能会在不同线程中的调用者产生冲突。 可用的清除策略有 LRU – 最近最少使用移除最长时间不被使用的对象。FIFO – 先进先出按对象进入缓存的顺序来移除它们。SOFT – 软引用基于垃圾回收器状态和软引用规则移除对象。WEAK – 弱引用更积极地基于垃圾收集器状态和弱引用规则移除对象。 *** 默认的清除策略是 LRU。*** 源文档: https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache settings!-- 标准的日志工厂实现--setting namelogImpl valueSTDOUT_LOGGING/!-- 显示开启全局缓存--setting namecacheEnabled valuetrue/
/settings然后Mapper中添加 cache可以带上上面的参数
原理 8.EhCache EhCache 是一个纯Java的进程内缓存框架具有快速、精干等特点是Hibernate中默认CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。 导包 !-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache --dependencygroupIdorg.mybatis.caches/groupIdartifactIdmybatis-ehcache/artifactIdversion1.2.2/version/dependency写入配置文件(resources-ehcache.xml) ?xml version1.0 encodingUTF-8?ehcache xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:noNamespaceSchemaLocationhttp://ehcache.org/ehcache.xsd!-- 磁盘缓存位置 --diskStore pathjava.io.tmpdir/ehcache/!-- 默认缓存 --defaultCachemaxEntriesLocalHeap10000eternalfalsetimeToIdleSeconds120timeToLiveSeconds120maxEntriesLocalDisk10000000diskExpiryThreadIntervalSeconds120memoryStoreEvictionPolicyLRUpersistence strategylocalTempSwap//defaultCache!-- helloworld缓存 --cache nameHelloWorldCachemaxElementsInMemory1000eternalfalsetimeToIdleSeconds5timeToLiveSeconds5overflowToDiskfalsememoryStoreEvictionPolicyLRU//ehcache在Mapper中指定 cache typeorg.mybatis.caches.ehcache.EhcacheCache/在实际开发中我们更多的使用Redis来做缓存