ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Mybatis实验

2021-11-19 12:34:46  阅读:142  来源: 互联网

标签:studentid 记录 System println 实验 student Mybatis out


二.Mybatis实验

1.项目结构

image-20211119120402686

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

标签:studentid,记录,System,println,实验,student,Mybatis,out
来源: https://www.cnblogs.com/dss-99/p/15576582.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有