金长 2019-05-28 11:48 采纳率: 0%
浏览 1805
已采纳

Mybatis小练习 报错 求大神指导,信息详尽

UserMapper

public interface UserMapper {
    //根据id查询用户信息
    public User findUserById(int id) throws Exception;
    //根据用户名列查询用户列表
    public List<User> findUserByName(String name)throws Exception;
    //插入用户
    public void insertUser(User user)throws Exception;

}

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">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace等于mapper接口地址
-->
<mapper namespace="com.neuedu.mapper.UserMapper">



    <!-- 在 映射文件中配置很多sql语句 -->
    <!-- 需求:通过id查询用户表的记录 -->
    <!-- 通过 select执行数据库查询
    id:标识 映射文件中的 sql
    将sql语句封装到mappedStatement对象中,所以将id称为statement的id
    parameterType:指定输入 参数的类型,这里指定int型 
    #{}表示一个占位符号
    #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称

    resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
     -->
    <select id="findUserById" parameterType="int" resultType="user">
        SELECT * FROM user WHERE id=#{value}
    </select>



    <!-- 根据用户名称模糊查询用户信息,可能返回多条
    resultType:指定就是单条记录所映射的java对象 类型
    ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
    使用${}拼接sql,引起 sql注入
    ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value
     -->
    <select id="findUserByName" parameterType="java.lang.String" resultType="com.neuedu.pojo.User">
        SELECT * FROM user WHERE username LIKE '%${value}%'
    </select>

    <!-- 添加用户 
    parameterType:指定输入 参数类型是pojo(包括 用户信息)
    #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值
    -->
    <insert id="insertUser" parameterType="com.neuedu.pojo.User">
        <!-- 
        将插入数据的主键返回,返回到user对象中

        SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键

        keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
        order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
        resultType:指定SELECT LAST_INSERT_ID()的结果类型
         -->
        insert into user(id,username,birthday,sex,address) values (seq_user.nextval,#{username},#{birthday},#{sex},#{address})
        <!-- 插入数据后,返回自动增长列的ID值,将sql语句的返回值赋给parameterType绑定对象的ID属性
              MySQL中使用:  select LAST_INSERT_ID() -->
        <selectKey keyProperty="id" order="AFTER" resultType="int">
            SELECT LAST_INSERT_ID()
            <!--select seq_user.currval from dual-->
        </selectKey>
        <!-- 
        使用mysql的uuid()生成主键
        执行过程:
        首先通过uuid()得到主键,将主键设置到user对象的id属性中
        其次在insert执行时,从user对象中取出id属性值
         -->
        <!--  <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
            SELECT uuid()
        </selectKey>
        insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) -->


    </insert>

    <!-- 删除 用户
    根据id删除用户,需要输入 id值
     -->
    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>

    <!-- 根据id更新用户
    分析:
    需要传入用户的id
    需要传入用户的更新信息
    parameterType指定user对象,包括 id和更新信息,注意:id必须存在
    #{id}:从输入 user对象中获取id属性值
     -->
    <update id="updateUser" parameterType="com.neuedu.pojo.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
         where id=#{id}
    </update>

</mapper>



Tset

public class UserMapperTest {

    private SqlSessionFactory sqlSessionFactory;

    // 此方法是在执行testFindUserById之前执行
    @Before
    public void setUp() throws Exception {
        // 创建sqlSessionFactory

        // mybatis配置文件
        String resource = "config/SqlMapConfig.xml";
        // 得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 创建会话工厂,传入mybatis的配置文件信息
        sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);
    }




    @Test
    public void testFindUserById() throws Exception {

        SqlSession sqlSession = sqlSessionFactory.openSession();

        //创建UserMapper对象,mybatis自动生成mapper代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //调用userMapper的方法
        User user = userMapper.findUserById(1);

        System.out.println(user);


    }


    @Test
    public void testFindUserByName() throws Exception {

        SqlSession sqlSession = sqlSessionFactory.openSession();

        //创建UserMapper对象,mybatis自动生成mapper代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //调用userMapper的方法

        List<User> list = userMapper.findUserByName("袁超");

        sqlSession.close();

        System.out.println(list);

    }


}

报错信息

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - Class not found: org.jboss.vfs.VFS
DEBUG [main] - JBoss 6 VFS API is not available in this environment.
DEBUG [main] - Class not found: org.jboss.vfs.VirtualFile
DEBUG [main] - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
DEBUG [main] - Using VFS adapter org.apache.ibatis.io.DefaultVFS
DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo
DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo
DEBUG [main] - Reader entry: User.class
DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo
DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo/User.class
DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo/User.class
DEBUG [main] - Reader entry: ����   1 N
DEBUG [main] - Checking to see if class com.neuedu.pojo.User matches criteria [is assignable to Object]
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper
DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper
DEBUG [main] - Reader entry: UserMapperTest.class
DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper
DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper/UserMapperTest.class
DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper/UserMapperTest.class
DEBUG [main] - Reader entry: ����   1 a
DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper
DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper
DEBUG [main] - Reader entry: UserMapper.class
DEBUG [main] - Reader entry: UserMapper.xml
DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper
DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.class
DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.class
DEBUG [main] - Reader entry: ����   1    findUserById (I)Lcom/neuedu/pojo/User; 
DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.xml
DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.xml
DEBUG [main] - Reader entry: <?xml version="1.0" encoding="UTF-8" ?>
DEBUG [main] - Checking to see if class com.neuedu.mapper.UserMapperTest matches criteria [is assignable to Object]
DEBUG [main] - Checking to see if class com.neuedu.mapper.UserMapper matches criteria [is assignable to Object]
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 209833425.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@c81cdd1]
DEBUG [main] - ==>  Preparing: SELECT * FROM T_USER WHERE username LIKE '%袁超%' 
DEBUG [main] - ==> Parameters: 

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist
### The error may exist in com/neuedu/mapper/UserMapper.xml
### The error may involve com.neuedu.mapper.UserMapper.findUserByName-Inline
### The error occurred while setting parameters
### SQL: SELECT * FROM T_USER WHERE username LIKE '%袁超%'
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist

    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
    at com.sun.proxy.$Proxy3.findUserByName(Unknown Source)
    at com.neuedu.mapper.UserMapperTest.testFindUserByName(UserMapperTest.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
    at com.mysql.jdbc.Util.getInstance(Util.java:383)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
    at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1193)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
    at com.sun.proxy.$Proxy5.execute(Unknown Source)
    at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
    at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
    at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
    at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
    at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
    ... 29 more

SqlMapConfig.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>

    <!-- 加载属性文件 -->
    <properties resource="db.properties">
        <!--properties中还可以配置一些属性名和属性值  -->
        <!-- <property name="jdbc.driver" value=""/> -->
    </properties>
    <!-- 全局配置参数,需要时再设置 -->
    <!-- <settings>

    </settings> -->

    <!-- 别名定义 -->
    <typeAliases>

        <!-- 针对单个别名定义
        type:类型的路径
        alias:别名
         -->
        <!-- <typeAlias type="com.neuedu.mybatis.po.User" alias="user"/> -->
        <!-- 批量别名定义 
        指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)
        -->
        <package name="com.neuedu.pojo"/>

    </typeAliases>

    <!-- 和spring整合后 environments配置将废除-->
    <environments default="development">
        <environment id="development">
        <!-- 使用jdbc事务管理,事务控制由mybatis-->
            <transactionManager type="JDBC" />
        <!-- 数据库连接池,由mybatis管理-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 加载 映射文件 -->
    <mappers>
        <mapper resource="sqlmap/User.xml"/>

        <!--通过resource方法一次加载一个映射文件 -->
        <!-- <mapper resource="sqlmap/User.xml"/> -->

        <!-- 通过mapper接口加载单个 映射文件
        遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
        上边规范的前提是:使用的是mapper代理方法
         -->
        <!-- <mapper class="com.neuedu.mapper.UserMapper"/> -->

        <!-- 批量加载mapper
        指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载
        遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
        上边规范的前提是:使用的是mapper代理方法
         -->
        <package name="com.neuedu.mapper"/>

    </mappers>

</configuration>

User

public class User {

    //属性名和数据库表的字段对应
    private int id;
    private String username;// 用户姓名
    private String sex;// 性别
    private Date birthday;// 生日
    private String address;// 地址
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", sex=" + sex
                + ", birthday=" + birthday + ", address=" + address + "]";
    }


}

也不知道为什么,明明已经在UserMapper.xml里面把表名改了,但是报错信息里查找的还是T-user表
求大神指导!感恩!

问题已解决

在maven文件里加上下面的代码

    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*Mapper.xml</include>
            </includes>
        </resource>
    </resources>
  • 写回答

3条回答 默认 最新

  • soulkeyboard 2019-05-28 12:29
    关注

    你要看你配置文件的数据源配置 DataSource 连接的是哪个数据库,你连接的应该是mybatis数据库 但是这个数据库内不存在 user表

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘