发表于: 2021-11-02 00:00:27

2 931


今天完成的事 实现mybatis查询数据库

用Navicat 创建数库mybatis

创建表单user

设计设置列表格式

用IDEA新建项目

目录结构为

编辑pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
   <artifactId>mybatistast</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <maven.compiler.source>17</maven.compiler.source>
       <maven.compiler.target>17</maven.compiler.target>
   </properties>
   <dependencies>
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.11</version>
       </dependency>
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.6</version>
       </dependency>
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.13.2</version>
           <scope>test</scope>
       </dependency>
       <dependency>
           <groupId>log4j</groupId>
           <artifactId>log4j</artifactId>
           <version>1.2.17</version>
       </dependency>
       <dependency>
           <groupId>org.junit.jupiter</groupId>
           <artifactId>junit-jupiter</artifactId>
           <version>RELEASE</version>
           <scope>compile</scope>
       </dependency>
       <dependency>
           <groupId>org.junit.jupiter</groupId>
           <artifactId>junit-jupiter</artifactId>
           <version>RELEASE</version>
           <scope>compile</scope>
       </dependency>
   </dependencies>
   <build>
       <resources>
           <resource>
               <directory>src/main/java</directory>
               <includes>
                   <include>**/*.properties</include>
                   <include>**/*.xml</include>
               </includes>
               <filtering>false</filtering>
           </resource>
       </resources>
   </build>

</project>

创建SqlMapConfig.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration >
   <settings>
       <setting name="logImpl" value="LOG4J"/>
   </settings>
   <!-- 和Spring整合后envirnmentss 配置将被移除-->
   <environments default="mysql">
       <environment id="mysql">
           <!-- 使用jdbc事务管理-->
           <transactionManager type="JDBC"/>
           <!-- 数据库连接池-->
           <dataSource type="POOLED">
               <property name="driver" value="com.mysql.jdbc.Driver"/>
               <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
               <property name="username" value="root"/>
               <property name="password" value="deng796443"/>
           </dataSource>
       </environment>
   </environments>
   <!-- 写完SQL映射文件后为了能让mybatis资源文件加载类解析Mapper文件-->
   <mappers>
       <mapper resource="UserMapper.xml"/>
   </mappers>
</configuration>

创建SQL映射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">

<mapper namespace="test">
   <select id="usersId" parameterType="int" resultType="Dao.User">
       select * from user where id =#{id}
</select>
</mapper>

创建实体类User.java

package Dao;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private int id;
   public  User(int id, String username, String password, String gender,
                String email, String province, String city, Date birthday)
{
super();
       this.id=id;
       this.username=username;
       this.gender=gender;
       this.email=email;
       this.province=province;
       this.password=password;
       this.city=city;
       this.birthday=birthday;
   }
public void setProvince(String province) {
this.province = province;
   }
public String getUsername() {
return username;
   }
public void setUsername(String username) {
this.username = username;
   }
private String username;
   public String getPassword() {
return password;
   }
public void setPassword(String password) {
this.password = password;
   }
private String password;
   public String getGender() {
return gender;
   }
public void setGender(String gender) {
this.gender = gender;
   }
private String gender;
   public String getEmail() {
return email;
   }
public void setEmail(String email) {
this.email = email;
   }
private String email;
   private String province;
   public String getCity() {
return city;
   }
public void setCity(String city) {
this.city = city;
   }
private String city;
   public Date getBirthday() {
return birthday;
   }
public void setBirthday(Date birthday) {
this.birthday = birthday;
   }
private Date birthday;
   public int getId() {
return id;
   }
public void setId(int id) {
this.id = id;
   }
}

创建数据库交互DataConnection.java

package Dao;
import java.io.IOException;
import java.io.InputStream;
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 DataConnection {
private String resource= "SqlMapConfig.xml";
   private SqlSessionFactory sqlSessionFactory;
   private SqlSession sqlSession;
   public SqlSession getSqlSession() throws IOException{
InputStream inputStream= Resources.getResourceAsStream(resource);
       //创建会话工厂,传入MyBatis配置文件信息
       sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
       sqlSession=sqlSessionFactory.openSession();
       return sqlSession;
   }
}

创建测试用例

import  java.io.IOException;
import  java.text.SimpleDateFormat;
import Dao.DataConnection;
import Dao.User;
import  org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

public class MyBatisTest {
public DataConnection dataConnection=new DataConnection();
   @Test
   public void TestSelect() throws IOException{
SqlSession sqlSession=dataConnection.getSqlSession();
           //最终结果与映射文件中所匹配的resultType类型
       User user=sqlSession.selectOne("test.usersId",1);
       System.out.println("姓名:"+user.getUsername());
       System.out.println("性别:"+user.getGender());
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
       System.out.println("生日:"+sdf.format(user.getBirthday()));
       System.out.println("所在地:"+user.getCity());
       sqlSession.close();


   }
}

最终输出结果

 明天的任务:学习一对多查询

今天遇到的问题:

运行报错
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for test.usersId
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for test.usersId 

mybatis.xml 找不到映射地址

添加下mapper 源地址后查询终于跑起来了
<mappers>
    <mapper resource="UserMapper.xml" />
</mappers> 

今天的收获

知道了找bug的方法与测试程序的方法

知道了

User user=sqlSession.selectOne("test.usersId",1);

sqlSession的selectOne方法有两个参数,第一个参数是SQL映射文件UserMapper.xml中的namespace加上statement配置的id

第二个参数是SQL映射文件中所匹配parameterType类型的参数。执行selectOne之后的结果为SQL映射文件中所匹配的resultType类型。

test.userId中的test对应的是namespace值,usersId 对应的是id

<mapper namespace="test">
   <select id="usersId" parameterType="int" resultType="Dao.User">
       select * from user where id =#{id}

</select>



返回列表 返回列表
评论

    分享到