DAY1-24.3.7 maven的回顾 将电脑中maven删除,本地仓库全部删除,注意.m下的默认仓库设置,再将系统环境中关于maven的全部删除,
下载maven的安装包,直接解压,conf下的settings.xml换个国内的阿里源
1 2 3 4 5 6 <mirror> <id >aliyunmaven</id > <mirrorOf>*</mirrorOf> <name>阿里云公共仓库</name> <url>[https://maven.aliyun.com/repository/public](https://maven.aliyun.com/repository/public)</url> </mirror>
设置环境变量
变量名:MAVEN_HOME
变量值:D:\Environment\maven-3.8.1\apache-maven-3.8.1
配置Path,双击打开Path—>新建 输入: %MAVEN_HOME%\bin 以管理员身份打开shell 输入:mvn -v 查看maven的版本信息,证明配置成功。
配置maven环境
创建一个名为myRepository的文件夹。修改settings.xml配置文件,位置在\conf目录下。
使用记事本打开settings.xml,将文件中的所有信息替换为如下,并保存后退出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 <?xml version="1.0" encoding="UTF-8" ?> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd" > <!-- <localRepository>/Users/Fred/Downloads/apache-maven-3.5 .4 /repository</localRepository> --> <localRepository>D:/Environment/maven-3.8 .1 /myRepository</localRepository> <pluginGroups> </pluginGroups> <proxies> </proxies> <servers> </servers> <mirrors> <mirror> <id >alimaven</id > <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> <mirror> <id >aliyun</id > <mirrorOf>central</mirrorOf> <name>aliyun-public</name> <url>https://maven.aliyun.com/repository/public/</url> </mirror> <mirror> <id >aliyun-spring</id > <mirrorOf>spring</mirrorOf> <name>aliyun-spring</name> <url>https://maven.aliyun.com/repository/spring</url> </mirror> <!-- 中央仓库在中国的镜像 --> <mirror> <id >maven.net.cn</id > <name>one of the central mirrors in china</name> <url>http://maven.net.cn/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> <!-- 中央仓库1 --> <mirror> <id >repo1</id > <mirrorOf>central</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>https://repo1.maven.org/maven2/</url> </mirror> </mirrors> <profiles> <profile> <id >jdk-1.8 </id > <activation> <activeByDefault>true</activeByDefault> <jdk>1.8 </jdk> </activation> <properties> <maven.compiler.source>1.8 </maven.compiler.source> <maven.compiler.target>1.8 </maven.compiler.target> <maven.compiler.compilerVersion>1.8 </maven.compiler.compilerVersion> </properties> </profile> </profiles> <activeProfiles> <activeProfile>jdk-1.8 </activeProfile> </activeProfiles> </settings>
打开cmd,执行:mvn help:system
此时本地仓库就会从中央仓库下载需要的文件。直到出现build success
IDAE操作数据库 新建一个数据源,选择mysql的数据源,配置好相关信息后,出现console的文件,设计相关代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 create database mybatis;use mybatis; create table user ( id int (10 ) primary key auto_increment comment '用户ID' , name varchar (40 ) not null comment '用户名' , pwd varchar (40 ) not null comment '密码' ); select * from user ;insert into user (name, pwd)values ('张三1号' , '123456' ), ('张三2号' , '123456' ), ('张三3号' , '123456' ), ('张三4号' , '123456' ), ('张三5号' , '123456' ), ('张三6号' , '123456' ), ('张三7号' , '123456' ); insert into user (id, name, pwd) values (?,?,?)
一个快捷键的回顾:alt实现多选。
JDBC操作数据库实例 接下来写主函数操作数据库的代码情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package com.neuedu;import java.sql.*;public class JDBCTest01 { public static void main (String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:3306/mybatis" ; String username = "root" ; String password = "123456" ; Class.forName("com.mysql.jdbc.Driver" ); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); String sql = "select * from user" ; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ System.out.println("编号=" +resultSet.getInt("id" )); System.out.println("用户名=" +resultSet.getString("name" )); System.out.println("密码=" +resultSet.getString("pwd" )); } resultSet.close(); statement.close(); connection.close(); } }
快捷的输入方式psvm,即public static void main(String[] args) {}
快捷的输入方式sout,即System.*out*.println();
选择驱动都可以
输出的结果 出现红色报错 存在的是驱动的引用问题。替换成'com.mysql.cj.jdbc.Driver'
就解决了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 "C:\Program Files\Java\jdk1.8.0_221\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2023.2.3\lib\idea_rt.jar=41969:C:\Program Files\JetBrains\IntelliJ IDEA 2023.2.3\bin" -Dfile.encoding=GBK -classpath "C:\Program Files\Java\jdk1.8.0_221\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\rt.jar;D:\GoodGoodStudy\21pro_practice\new1\Mybatis_Study\mybatis-jdbc-01\target\classes;C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\8.0.27\mysql-connector-java-8.0.27.jar;C:\Users\Administrator\.m2\repository\com\google\protobuf\protobuf-java\3.11.4\protobuf-java-3.11.4.jar" com.neuedu.JDBCTest01Loading 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. 编号=1 用户名=张三1号 密码=123456 编号=2 用户名=张三2号 密码=123456 编号=3 用户名=张三3号 密码=123456 编号=4 用户名=张三4号 密码=123456 编号=5 用户名=张三5号 密码=123456 编号=6 用户名=张三6号 密码=123456 编号=7 用户名=张三7号 密码=123456 进程已结束,退出代码为 0
预编译,sql中使用?代替
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package com.neuedu;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;public class JDBCTest02 { public static void main (String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:3306/mybatis" ; String username = "root" ; String password = "123456" ; Class.forName("com.mysql.cj.jdbc.Driver" ); Connection connection = DriverManager.getConnection(url, username, password); String sql = "insert into user(id, name, pwd) values(?,?,?)" ; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1 ,8 ); preparedStatement.setString(2 ,"root" ); preparedStatement.setString(3 ,"123456" ); int count = preparedStatement.executeUpdate(); if (count>0 ){ System.out.println("插入成功success!!" ); } preparedStatement.close(); connection.close(); } }
Day2-24.3.12 mybatis官网学习核心配置文件 先创建一个MyBatis-config.xml的配置文件,但其中需要修改数据库driver、url、username、password的信息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?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.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml" /> </mappers> </configuration>
在此之前需要创建一个用作实体类的文件。
创建pojo软件包存放实体类文件:
实体的属性私有
get()与set()方法的定义
toString()方法的定义
有参构造与无参构造函数的定义(有参构造alt+insert全选,无参构造则全部选 ctrl)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 package com.neuedu.pojo;public class User { private Integer id; private String name; private String pwd; public Integer getId () { return id; } public void setId (Integer 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; } @Override public String toString () { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}' ; } public User () { } public User (Integer id, String name, String pwd) { this .id = id; this .name = name; this .pwd = pwd; } }
mybatis工具类编写 创建utils组件软件包,其中创建MybatisUtils的java类,创建sqlSessionFactory,建立数据库的连接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package com.neuedu.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 { private static SqlSessionFactory sqlSessionFactory; static { String resource = "mybatis-config.xml" ; try { InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory=new SqlSessionFactoryBuilder ().build(inputStream); } catch (IOException e) { throw new RuntimeException (e); } } public static SqlSession getSqlSession () { return sqlSessionFactory.openSession(); } public static void setSqlSessionFactory (SqlSessionFactory sqlSessionFactory) { MyBatisUtils.sqlSessionFactory = sqlSessionFactory; } }
接口定义接口映射文件 定义命名空间所需要的数据访问层接口,这里设定的是程序使用的UserDao接口,包括程序使用的一些函数的定义,包括用户的查询,插入新用户,修改用户等方法的定义,接着就是创建接口映射文件UserDao.xml。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package com.neuedu.dao;import com.neuedu.pojo.User;import java.util.List;public interface UserDao { List<User> getUserList () ; User getUserById (Integer id) ; int addUser (User user) ; int deleteUser (Integer id) ; int updateUser (User user) ; int deleteUserByName (String name) ; List<User> getUserLike (String name) ; }
创建的UserDao.xml文件的具体代码如下:
用于具体方法的定义,即数据库的sql语句的具体使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?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.neuedu.dao.UserDao" ><!--namespace 需要绑定数据访问层的接口--> <!--<select id="selectBlog" resultType="Blog" > select * from Blog where id = #{id} 写自己的查询语句 </select>--> <select id="getUserList" resultType="com.neuedu.pojo.User" > select * from user </select> <select id="getUserById" resultType="com.neuedu.pojo.User" parameterType="int" > select * from user where id=#{id} </select> </mapper>
mybatis实现数据查询 test软件包下的java文件中创建一个test文件用于实现数据的查询:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import com.neuedu.dao.UserDao;import com.neuedu.pojo.User;import com.neuedu.utils.MyBatisUtils;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Test;import java.util.List;public class MyTest { @Test public void getUserList () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> userList=mapper.getUserList(); System.out.println(userList); sqlSession.close(); } @Test public void getUserById () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); User user = mapper.getUserById(1 ); System.out.println(user); sqlSession.close(); } }
其中需要更新配置依赖,junit构建单元测试的注解,配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 <dependency > <groupId > junit</groupId > <artifactId > junit</artifactId > <version > 4.13.1</version > <scope > test</scope > </dependency > <dependency > <groupId > org.junit.jupiter</groupId > <artifactId > junit-jupiter</artifactId > <version > 5.8.1</version > <scope > test</scope > </dependency >
当然,如果在此情况下,仍然出现无法连接并查到数据的情况,则需要加上一个maven的过滤装置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > true</filtering > </resource > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > true</filtering > </resource > </resources > </build >
作业完成 1.插入一个新用户:在UserDao接口类中定义插入用户的函数方法,接着在UserDao.xml文件中写出mybatis的sql语句,记住标签要随着sql语句的内容进行更改,代码如下:
1 2 3 4 int addUser (User user) ;
1 2 3 4 <insert id ="addUser" parameterType ="com.neuedu.pojo.User" > insert into user(id,name,pwd) values(#{id},#{name},#{pwd}) </insert >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 @Test public void addUser () { SqlSession sqlSession=MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int flag=mapper.addUser(new User (24 ,"张三" ,"852963" )); if (flag>0 ){ System.out.println("insert success" ); } sqlSession.commit(); sqlSession.close(); } @Test public void addUser () { SqlSession sqlSession=MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int adduser=mapper.addUser(new User (23 ,"张三" ,"852963" )); System.out.println(adduser); System.out.println("insert success" ); sqlSession.commit(); sqlSession.close(); }
2.删除一个用户 根据ID:在UserDao接口类中定义插入用户的函数方法,接着在UserDao.xml文件中写出mybatis的sql语句,记住标签要随着sql语句的内容进行更改,注意sql语句的书写,代码如下:
1 2 3 4 int deleteUser (Integer id) ;
1 2 3 4 5 6 <delete id ="deleteUser" parameterType ="com.neuedu.pojo.User" > delete from user where id=#{id} </delete >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Test public void deleteUser () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int flag = mapper.deleteUser(23 ); if (flag>0 ){ System.out.println("delete success" ); } sqlSession.commit(); sqlSession.close(); }
3.修改一个用户:在UserDao接口类中定义插入用户的函数方法,接着在UserDao.xml文件中写出mybatis的sql语句,记住标签要随着sql语句的内容进行更改,注意sql语句的书写,代码如下:
1 2 3 4 5 int updateUser (User user) ;
1 2 3 4 5 6 <update id ="updateUser" parameterType ="com.neuedu.pojo.User" > update user set name=#{name},pwd=#{pwd} where id=#{id} </update >
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void updateUser () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int updateUser = mapper.updateUser(new User (23 ,"ZhangSan" ,"123456" )); System.out.println(updateUser); System.out.println("update success" ); sqlSession.commit(); sqlSession.close(); }
4.根据名字删除用户:在UserDao接口类中定义插入用户的函数方法,接着在UserDao.xml文件中写出mybatis的sql语句,记住标签要随着sql语句的内容进行更改,注意sql语句的书写,代码如下:
1 2 3 4 int deleteUserByName (String name) ;
1 2 3 4 5 6 <delete id ="deleteUserByName" parameterType ="com.neuedu.pojo.User" > delete from user where name=#{name} </delete >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Test public void deleteUserByName () { SqlSession sqlSession= MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); int deleteUserByName= mapper.deleteUserByName("ZhangSan" ); System.out.println(deleteUserByName); System.out.println("deleteByName success" ); sqlSession.commit(); sqlSession.close(); }
5.根据姓名模糊查询:在UserDao接口类中定义插入用户的函数方法,接着在UserDao.xml文件中写出mybatis的sql语句,记住标签要随着sql语句的内容进行更改,注意sql语句的书写,代码如下:
1 2 3 4 List<User> getUserLike (String name) ;
1 2 3 4 5 <select id ="getUserLike" parameterType ="com.neuedu.pojo.User" > select * from user where name like "%"#{name}"%"; </select >
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void getUserLike () { SqlSession sqlSession= MyBatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> userLike = mapper.getUserLike("%张%" ); for (User user : userLike) { System.out.println(user); } sqlSession.close(); }
Day3-24.3.21 核心配置文件、environment元素、mapper元素 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 <configuration > <properties resource ="db.properties" /> <settings > <setting name ="logImpl" value ="LOG4J" /> </settings > <typeAliases > <package name ="com.neuedu.pojo" /> </typeAliases > <environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="${driver}" /> <property name ="url" value ="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8" /> <property name ="username" value ="${username}" /> <property name ="password" value ="${password}" /> </dataSource > </environment > </environments > <mappers > <package name ="com.neuedu.mapper" /> </mappers > </configuration >
Properties优化 在resource文件中创建一个db.properties文件作为properties优化配置文件,输入数据库的相关配置信息
1 2 3 4 driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql: username=root password=123456
上面的优化配置文件写好后,就可以直接在config数据库的配置信息进行引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <configuration> <properties resource="db.properties" /> <typeAliases> <!--配置别名--> <!-- <typeAlias type="com.neuedu.pojo.User" alias="User" />--> <!--扫描实体类的包--> <typeAlias type="com.neuedu.pojo" /> </typeAliases> <!--环境配置文件--> <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> <mappers> <!--mapper映射文件绑定--> <!--1. 扫描mapper映射文件绑定注册 --> <!-- <mapper resource="com/neuedu/mapper/UserMapper.xml" />--> <!--2. class文件 接口文件和mapper映射文件同名且同包--> <!-- <mapper class="com.neuedu.mapper.UserMapper" />--> <!--3. 扫描包绑定注册 --> <package name="com.neuedu.mapper" /> <!--4. 使用完全限定资源定位符url绑定绝对路径 不建议 --> <!-- <mapper url="D:\GoodGoodStudy\21pro_practice\new1\Mybatis_Study\mybatis-02\src\main\java\com\neuedu\dao\UserDao.xml" />--> </mappers> </configuration>
出现报错,解析发现需要规定配置标签的顺序
配置别名typeAliases 1 2 3 4 5 6 7 8 9 <typeAliases > <package name ="com.neuedu.pojo" /> </typeAliases >
一种是type使用具体的类名,比较麻烦,批量起来麻烦(标签:typeAlias type )
另一种是直接扫描实体包所在文件夹(这里的标签是package name )
注意不要搞混了,否则容易出现报错的情况。(如下的一种报错情况)
1 Could not resolve type alias ''. Cause: java.lang.ClassNotFoundException: Cannot find class:
Day4-24.3.26 使用注解 引入依赖lombok
1 2 3 4 5 6 7 <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18 .30 </version> </dependency> </dependencies>
使用注解构建实体类的方法(User.java),如下代码种所示的三种注解,分别对应注释下的信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.neuedu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String name; private String password; }
使用注解构建实体的映射方法(UserMapper.java),使用注解的方式省略映射文件的编写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 package com.neuedu.mapper;import com.neuedu.pojo.User;import org.apache.ibatis.annotations.*;import java.util.List;@Mapper public interface UserMapper { @Select("select * from user") List<User> getUserList () ; @Select("select * from user where id=#{id}") User getUserById (Integer id) ; @Insert("insert into user(name,pwd) values(#{name},#{pwd})") int addUser (User user) ; @Delete("delete from user where id=#{id}") int deleteUser (Integer id) ; @Update("update user set name=#{name},pwd=#{pwd} where id=#{id}") int updateUser (User user) ; @Delete("delete from user where name=#{name}") int deleteUserByName (String name) ; @Select("select * from user where name like concat('%',#{name},'%')") List<User> getUserLike (String name) ; }
使用resultMap实现映射 用以解决实体类属性名与数据库表中字段名不一致的情况,查询结果映射成实体对象
column 从数据库中查询到的结果集的列名或列别名。
property 将 column属性指定的列结果映射到对象的哪个属性
1 2 3 4 public class User { private Integer id; private String name; private String password;
1 2 3 4 5 6 7 8 9 10 11 12 <!--1. 简单的AS语句--> <!-- <select id="getUserById" resultType="com.neuedu.pojo.User" parameterType="int" >--> <!-- select id,name,pwd AS password from user where id=#{id}--> <!-- </select>--> <!--2. 通过resultMap实现 --> <resultMap id="userMap" type="com.neuedu.pojo.User" > <result column="id" property="id" /> <result column="name" property="name" /> <result column="pwd" property="password" /> <!--column 数据库表字段,property实体类属性--> </resultMap>
实体类中使用的password,而数据库中定义的是pwd,所以使用resultMap来映射实体对象
分页 分页限制 使用RowBounds进行分页处理,是将所有符合条件的数据全都查询到内存中,然后在内存中对数据进行分页,若数据量大,千万别使用RowBounds
1 2 List<User> getUserLimit (Map<String,Integer> map) ;
1 2 3 <select id="getUserLimit" parameterType="map" resultMap="userMap" > select * from user limit #{startIndex},#{pageSize} </select>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Test public void getUserLimit () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap <>(); map.put("startIndex" ,4 ); map.put("pageSize" ,4 ); List<User> userLimit = mapper.getUserLimit(map); for (User user : userLimit){ System.out.println(user); } sqlSession.close(); }
分页查询RowBounds 1 2 List<User> getUserRowBounds () ;
1 2 3 <select id="getUserRowBounds" resultMap="userMap" > select *from user </select>
1 2 3 4 5 6 7 8 9 10 11 @Test public void getUserRowBounds () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); RowBounds rowBounds = new RowBounds (4 , 5 ); List<User> userList = sqlSession.selectList("com.neuedu.mapper.UserMapper.getUserRowBounds" , null , rowBounds); for (User user:userList){ System.out.println(user); } sqlSession.close(); }
联合查询-Student&Teacher 小总结:引入前面的依赖和工具集utils
1 2 3 4 driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql: username=root password=123456
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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/neu.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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <?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 > <properties resource ="db.properties" /> <settings > <setting name ="logImpl" value ="LOG4J" /> </settings > <typeAliases > <package name ="com.neuedu.pojo" /> </typeAliases > <environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="${driver}" /> <property name ="url" value ="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8" /> <property name ="username" value ="${username}" /> <property name ="password" value ="${password}" /> </dataSource > </environment > </environments > <mappers > <package name ="com.neuedu.mapper" /> </mappers > </configuration >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package com.neuedu.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 { private static SqlSessionFactory sqlSessionFactory; static { String resource = "mybatis-config.xml" ; try { InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory=new SqlSessionFactoryBuilder ().build(inputStream); } catch (IOException e) { throw new RuntimeException (e); } } public static SqlSession getSqlSession () { return sqlSessionFactory.openSession(true ); } public static void setSqlSessionFactory (SqlSessionFactory sqlSessionFactory) { MyBatisUtils.sqlSessionFactory = sqlSessionFactory; } }
查询学生联合老师信息(多对一) 建立的实体类Student和Teacher,该情况下Student实体类下外加学生关联的老师属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.neuedu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer id; private String name; private Integer tid; private Teacher teacher; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package com.neuedu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Teacher { private Integer id; private String name; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <select id ="getStudentList2" resultMap ="studentTeacher2" > select * from stuednt </select > <resultMap id ="studentTeacher2" type ="student" > <result column ="tid" property ="tid" /> <association property ="teacher" column ="tid" javaType ="teacher" select ="getTeacher" /> </resultMap > <select id ="getTeacher" resultType ="teacher" > select id,name teacherName from teacher where id=#{tid} </select >
忘记加@Test
注解所以一时间没做运行
1 2 3 4 5 6 7 8 9 10 @Test public void getStudentList2 () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> studentList=mapper.getStudentList2(); for (Student student : studentList) { System.out.println(student); } sqlSession.close(); }
运行出的结果如下:
查询老师联合学生信息(一对多) 建立的实体类Student和Teacher,该情况下Teacher类中外加一个Student的列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.neuedu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer id; private String name; private Integer tid; private Teacher teacher; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.neuedu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.util.List;@Data @AllArgsConstructor @NoArgsConstructor public class Teacher { private Integer id; private String teachername; private List<Student> studentList; }
创建一个Mapper,根据老师ID获取老师信息以及老师对应的所有学生信息
1 2 3 4 5 6 7 8 9 10 11 package com.neuedu.mapper;import com.neuedu.pojo.Teacher;import org.apache.ibatis.annotations.Mapper;@Mapper public interface TeacherMapper { Teacher getTeacher (Integer id) ; }
接着创建mapper映射文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <resultMap id ="teacherStudent" type ="teacher" > <result column ="tid" property ="id" /> <result column ="tname" property ="teachername" /> <collection property ="studentList" ofType ="Student" > <result column ="sid" property ="id" /> <result column ="sname" property ="name" /> <result column ="tid" property ="tid" /> </collection > </resultMap > <select id ="getTeacher" resultMap ="teacherStudent" > select t.id tid,t.name tname,s.id sid,s.name sname from teacher t,stuednt s where t.id = s.tid and t.id=20240002 </select >
1 2 3 4 5 6 7 8 9 <resultMap id="studentTeacher" type="student" > <result column="sid" property="id" /> <result column="sname" property="name" /> <result column="tid" property="tid" /> <association property="teacher" javaType="teacher" > <result column="tid" property="id" /> <result column="tname" property="name" /> </association> </resultMap>
1 2 3 4 5 <select id="getStudentList" resultMap="studentTeacher" > select s.id as sid,s.name as sname,s.tid tid ,t.name tname from stuednt AS s,teacher as t where s.tid=t.id; </select>
Day5-24.4.9 动态SQL 通过if,choose,when,otherwise,trim, where, set, foreach等标签,组成灵活的sql语句,提高sql语句的准确性,创建一个blog数据库表
1 2 3 4 5 6 7 CREATE TABLE `blog` ( `id` varchar (50 ) NOT NULL COMMENT '博客id' , `title` varchar (100 ) NOT NULL COMMENT '博客标题' , `author` varchar (30 ) NOT NULL COMMENT '博客作者' , `create_time` datetime NOT NULL COMMENT '创建时间' , `views` int (30 ) NOT NULL COMMENT '浏览量' ) ENGINE= InnoDB DEFAULT CHARSET= utf8
com.neuedu.untils工具类下定义一个IDUtil类
1 2 3 4 5 6 7 8 9 10 package com.neuedu.utils;import java.util.UUID;public class IDUtil { public static String getId () { return UUID.randomUUID().toString().replaceAll("-" ,"" ); } }
定义Blog类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.neuedu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.util.Date;@Data @AllArgsConstructor @NoArgsConstructor public class Blog { private String id; private String title; private String author; private Date createTime; private Integer views; }
定义BlogMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 package com.neuedu.mapper;import com.neuedu.pojo.Blog;import java.util.List;import java.util.Map;public interface BlogMapper { int addBlog (Blog blog) ; List<Blog> queryBlogIf (Map map) ; }
设置驼峰命名法与全局缓存
1 2 3 4 <setting name ="mapUnderscoreToCamelCase" value ="true" /> <setting name ="cacheEnabled" value ="true" />
定义BlogMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?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.neuedu.mapper.BlogMapper" > <insert id ="addBlog" parameterType ="blog" > insert into blog (id, title, author, create_time, views) values (#{id},#{title},#{author},#{createTime},#{views}); </insert > <select id ="queryBlogIf" parameterType ="map" resultType ="blog" > select * from blog <where > <if test ="title != null" > title = #{title} </if > <if test ="author != null" > and author = #{author} </if > </where > </select > </mapper >
MyTest.java测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 import com.neuedu.mapper.BlogMapper;import com.neuedu.pojo.Blog;import com.neuedu.utils.IDUtil;import com.neuedu.utils.MyBatisUtils;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Test;import java.util.Date;import java.util.HashMap;import java.util.List;public class MyTest { @Test public void addBlog () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Blog blog = new Blog (); blog.setId(IDUtil.getId()); blog.setTitle("Mybatis" ); blog.setAuthor("吴老师" ); blog.setCreateTime(new Date ()); blog.setViews(20 ); mapper.addBlog(blog); blog.setId(IDUtil.getId()); blog.setTitle("Java" ); mapper.addBlog(blog); blog.setId(IDUtil.getId()); blog.setTitle("数据结构与算法" ); mapper.addBlog(blog); blog.setId(IDUtil.getId()); blog.setTitle("人工智能导论" ); mapper.addBlog(blog); sqlSession.close(); } @Test public void queryBlogIf () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap<String,String> map=new HashMap <>(); map.put("title" ,"Java" ); map.put("author" ,"Teacher liu" ); List<Blog> blogList=mapper.queryBlogIf(map); for (Blog blog:blogList){ System.out.println(blog); } sqlSession.close(); } }
缓存cache 一级缓存 本地缓存,与数据库同一次会话期间查询到的数据放在本地缓存,相同数据无需再次查询数据库。
示例
定义接口UserMapper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package com.neuedu.mapper;import com.neuedu.pojo.User;import org.apache.ibatis.annotations.Mapper;import java.util.List;import java.util.Map;@Mapper public interface UserMapper { User getUserById (Integer id) ; }
对应的xml文件
1 2 3 <select id="getUserById" resultType="com.neuedu.pojo.User" parameterType="int" > select * from user where id=#{id} </select>
测试用例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Test public void getUserById () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1 ); System.out.println(user); User user2 = mapper.getUserById(1 ); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); }
会发现第二次是直接在缓存中取得数据。
失效的情况(第二次再次查询数据库数据)
二级缓存
全局缓存,一级缓存作用域太低。
基于namespace级别的缓存,一个对应二级缓存的名称空间
第一步先开启的一个二级全局缓存:在【mybatis-config.xml】文件中
1 2 <setting name="cacheEnabled" value="true" />
在mapper.xml中使用二级缓存
1 <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Test public void getUserById05 () { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); SqlSession sqlSession2 = MyBatisUtils.getSqlSession(); UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class); User user = mapper.getUserById(1 ); User user2 = mapper2.getUserById(1 ); System.out.println(user=user2); sqlSession2.close(); sqlSession.close(); }
Day6-24.4.11上 Spring框架学习 Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。
组成:
核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory ,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文 包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了Spring框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不 同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包 括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结 构。
Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口, MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText和 POI
IOC学习 控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法 ,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。