二.Mybatis实验
1.项目结构
2.App代码
package cn.edu;
import java.io.InputStream;
import java.util.List;
import java.util.Scanner;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class App {
public static void main(String[] args) throws Exception {
//读取配置文件,并创建Mybatis的SqlSessionFactory对象实例
InputStream reader = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
// 取得一个SqlSession实例
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 取得CountryMapper映射器,映射器负责在数据表country与实体类Country之间建立对应关系
StudentMapper countrymapper = sqlSession.getMapper(StudentMapper.class);
//List<Student> countryList = sqlSession.selectList("selectAll");
// 查询country表中的所有记录
System.out.println("查询学生表中的所有记录");
showAll(countrymapper);
// 显示country表中指定的记录
System.out.println("显示student表中指定的记录");
System.out.println("请输入要查询记录的ID号:");
Scanner scanner = new Scanner(System.in);
Long id = scanner.nextLong();
Student student = (Student) countrymapper.selectOne(id);
System.out.println(
"test:" + student.getStudentid() + " " + student.getStudentname() + " " + student.getStudentclass());
// 向country表中插入一条记录
System.out.println("向student表中插入一条记录");
System.out.println("增加一条新的记录,按照<编号,姓名,班级>输入,以逗号分隔:");
String country_input = scanner.next();
System.out.println(country_input);
String[] country_list = country_input.split(",");
Student student_new = new Student();
student_new.setStudentid(Long.parseLong(country_list[0]));
student_new.setStudentname(country_list[1]);
student_new.setStudentclass(country_list[2]);
countrymapper.insertCountry(student_new);
sqlSession.commit(); // 不要忘记提交
System.out.println("显示student表中的所有记录");
showAll(countrymapper);
//刪除一条记录
System.out.println("请输入删除记录的ID号:");
id = scanner.nextLong();
countrymapper.deleteCountry(id);
sqlSession.commit(); // 不要忘记提交
System.out.println("显示student表中的所有记录");
showAll(countrymapper);
//更新一条记录
System.out.println("更新一条记录");
System.out.println("请输入更新学生的ID号:");
id = scanner.nextLong();
System.out.println("请输入新的学生名字:");
String name = scanner.next();
System.out.println("请输入新的学生班级:");
String code = scanner.next();
student_new.setStudentid(id);
student_new.setStudentname(name);
student_new.setStudentclass(code);
countrymapper.updateCountry(student_new);;
sqlSession.commit(); // 不要忘记提交
System.out.println("显示student表中的所有记录");
showAll(countrymapper);
} finally {
sqlSession.close();
}
}
// 查询country表中的所有记录
private static void showAll(StudentMapper countrymapper) {
List<Student> studentList = countrymapper.selectAll();
System.out.println("编号" + " 姓名 " + " 班级 ");
for (Student student : studentList)
System.out.println(student.getStudentid() + " "
+ student.getStudentname() + " "
+ student.getStudentclass());
}
}
3.student
package cn.edu;
public class Student {
private Long studentid;
private String studentname;
private String studentclass;
public Student(){}
public Long getStudentid() {
return studentid;
}
public void setStudentid(Long studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getStudentclass() {
return studentclass;
}
public void setStudentclass(String studentclass) {
this.studentclass = studentclass;
}
}
4.StudentMapper.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">
<mapper namespace="cn.edu.StudentMapper">
<!-- 查询所有记录 -->
<select id="selectAll" resultType="Student" >
select studentid,studentname,studentclass from student
</select>
<!-- 根据编号查询一条记录 -->
<select id="selectOne" resultType="Student" parameterType="Long">
select studentid,studentname,studentclass from student where studentid=#{studentid}
</select>
<!-- 插入记录 -->
<insert id="insertCountry" >
insert into student (studentid,studentname,studentclass)
values (#{studentid},#{studentname},#{studentclass})
</insert>
<!-- 更新记录 -->
<update id="updateCountry">
update student set
studentid = #{studentid},
studentname = #{studentname},
studentclass = #{studentclass}
where studentid = #{studentid}
</update>
<!-- 删除记录 -->
<delete id="deleteCountry">
delete from student where studentid = #{studentid}
</delete>
</mapper>
5.studentmapper
package cn.edu;
import java.util.List;
public interface StudentMapper {
//查询所有记录,对应CountryMapper.xml中的id="selectAll"
public List<Student> selectAll();
//根据编号查询一条记录,对应CountryMapper.xml中的id="selectOne"
public Student selectOne(Long id);
//插入记录,对应CountryMapper.xml中的id="insertCountry"
public void insertCountry(Student student);
//更新记录,对应CountryMapper.xml中的id="updateCountry"
public void updateCountry(Student student);
//删除记录,对应CountryMapper.xml中的id="deleteCountry"
public void deleteCountry(Long id);
}
6.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">
<configuration>
<!--mybatis配置文件的标签顺序必须是以下顺序:
The content of element type “configuration”
must match “(properties?,settings?,typeAliases?,
typeHandlers?,objectFactory?,objectWrapperFactory?,
reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)”.
-->
<!-- <properties resource="H2Config.properties" /> -->
<properties resource="MySQL8.properties" />
<!-- <properties resource="SQLiteConfig.properties" /> -->
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<package name="cn.edu" />
</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 resource="cn/edu/StudentMapper.xml"/> -->
<!-- 包下的所有映射器 -->
<package name="cn.edu" />
</mappers>
</configuration>
7.MySQL8.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaee_database?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
8.pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.edu</groupId>
<artifactId>MyBatisDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MyBatisDemo</name>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Mybatis框架的依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- 日志系统 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<!-- 以下为三种数据库的依赖 -->
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>cn.edu.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>assembly</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<id>copy-xmls</id>
<phase>process-sources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src/main/java/</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>${basedir}/src/main/java/</directory>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>cn.edu.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
</project>
8.运行结果
查询学生表中的所有记录
编号 姓名 班级
1 李四 1
2 王二 2
4 丁帅帅 4
显示student表中指定的记录
请输入要查询记录的ID号:
1
test:1 李四 1
向student表中插入一条记录
增加一条新的记录,按照<编号,姓名,班级>输入,以逗号分隔:
3,麻子,3
3,麻子,3
显示student表中的所有记录
编号 姓名 班级
1 李四 1
2 王二 2
4 丁帅帅 4
3 麻子 3
请输入删除记录的ID号:
4
显示student表中的所有记录
编号 姓名 班级
1 李四 1
2 王二 2
3 麻子 3
更新一条记录
请输入更新学生的ID号:
3
请输入新的学生名字:
小明
请输入新的学生班级:
5
显示student表中的所有记录
编号 姓名 班级
1 李四 1
2 王二 2
3 小明 5