麻烦老师帮我看看出了什么问题

麻烦老师帮我看看出了什么问题

@Test
public void testManyToOne(){
    SqlSession session = null;
    try{
        session = MyBatisUtils.openSession();
        List<GoodsDetail> list = session.selectList("goods_detail.selectManyToOne");
        for(GoodsDetail gd:list){
            System.out.println(gd.getGdPicUrl()+":"+gd.getGoods().getTitle() );
        }
    }catch(Exception e
    ){
        e.printStackTrace();
    }finally {
        MyBatisUtils.closeSession(session);
    }
}
<resultMap id="rmGoodsDetail" type="com.imooc.entity.GoodsDetail">
    <id column="gd_id" property="gdId"></id>
    <association property="goods" column="goods_id" select="goods.selectById"/>
</resultMap>
<select id="selectManyToOne" resultMap="rmGoodsDetail">
    select * from t_goods_detail limit 0,1
</select>
<select id="selectById" parameterType="Integer" resultType="com.imooc.entity.Goods">
    select * from t_goods where goods_id = #{value }
</select>
package com.imooc.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory=null;
     static {
         Reader reader = null;
         try {
             reader = Resources.getResourceAsReader("mybatis-config.xml");
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
         } catch (IOException e) {
             e.printStackTrace();
             throw new ExceptionInInitializerError(e);
         }

     }
         public static SqlSession openSession(){
             return sqlSessionFactory.openSession(true);
         }

         public static void closeSession(SqlSession session){
         if (session!=null){
             session.close();
             System.out.println("close执行");
         }
         }

}
<?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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/babytun?useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password"  value="123456"/>


            </dataSource>
        </environment>
        <environment id="student">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/student?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password"  value="123456"/>


            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/goods.xml"/>
        <mapper resource="mappers/student.xml"/>
        <mapper resource="mappers/goods_detail.xml"/>
    </mappers>
</configuration>
H:\jdk1.8\bin\java.exe -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:63556,suspend=y,server=n -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:C:\Users\ASUS\.IntelliJIdea2019.2\system\captureAgent\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "H:\IntelliJ IDEA 2019.2.4\lib\idea_rt.jar;H:\IntelliJ IDEA 2019.2.4\plugins\junit\lib\junit-rt.jar;H:\IntelliJ IDEA 2019.2.4\plugins\junit\lib\junit5-rt.jar;H:\jdk1.8\jre\lib\charsets.jar;H:\jdk1.8\jre\lib\deploy.jar;H:\jdk1.8\jre\lib\ext\access-bridge-64.jar;H:\jdk1.8\jre\lib\ext\cldrdata.jar;H:\jdk1.8\jre\lib\ext\dnsns.jar;H:\jdk1.8\jre\lib\ext\jaccess.jar;H:\jdk1.8\jre\lib\ext\jfxrt.jar;H:\jdk1.8\jre\lib\ext\localedata.jar;H:\jdk1.8\jre\lib\ext\nashorn.jar;H:\jdk1.8\jre\lib\ext\sunec.jar;H:\jdk1.8\jre\lib\ext\sunjce_provider.jar;H:\jdk1.8\jre\lib\ext\sunmscapi.jar;H:\jdk1.8\jre\lib\ext\sunpkcs11.jar;H:\jdk1.8\jre\lib\ext\zipfs.jar;H:\jdk1.8\jre\lib\javaws.jar;H:\jdk1.8\jre\lib\jce.jar;H:\jdk1.8\jre\lib\jfr.jar;H:\jdk1.8\jre\lib\jfxswt.jar;H:\jdk1.8\jre\lib\jsse.jar;H:\jdk1.8\jre\lib\management-agent.jar;H:\jdk1.8\jre\lib\plugin.jar;H:\jdk1.8\jre\lib\resources.jar;H:\jdk1.8\jre\lib\rt.jar;H:\SXClass\mybatis\target\test-classes;H:\SXClass\mybatis\target\classes;C:\Users\ASUS\.m2\repository\org\mybatis\mybatis\3.5.1\mybatis-3.5.1.jar;C:\Users\ASUS\.m2\repository\junit\junit\4.12\junit-4.12.jar;C:\Users\ASUS\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\ASUS\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;C:\Users\ASUS\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\ASUS\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\ASUS\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.imooc.mybatis.MyBatisTestor,testManyToOne
Connected to the target VM, address: '127.0.0.1:63556', transport: 'socket'

12:22:20.572 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
12:22:20.611 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
12:22:20.612 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
12:22:20.612 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
12:22:20.613 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.



java.lang.NoClassDefFoundError: Could not initialize class com.imooc.mybatis.utils.MyBatisUtils

	at com.imooc.mybatis.MyBatisTestor.testManyToOne(MyBatisTestor.java:247)
	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:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	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)


Disconnected from the target VM, address: '127.0.0.1:63556', transport: 'socket'

Process finished with exit code -1

这个是我今天写的,还有我昨天写的方法本来测试成功的,到了今天也不行了,也是这个错误,错误提示太笼统了,一般以前我遇到这个错误都是mapper写错了,但是这次真的找不到解决办法了,麻烦老师看一下

正在回答

登陆购买课程后可参与讨论,去登陆

7回答

http://img1.sycdn.imooc.com//climg/5dee2abd0964868c06770188.jpg

同学这里多了一个空格哦,同学修改一下就可以了


如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


好帮手慕阿莹 2019-12-09 12:23:57

同学你好,非常抱歉比较晚回复同学,因为报错比较模糊,老师也无法定位问题,只能依次放开代码去试,所以过程有点慢,还望同学多多包涵

经过多次调试,发现注释掉goods.xml中这两个方法后就可以正常运行了:

http://img1.sycdn.imooc.com//climg/5dedcbb809e38d5a07180267.jpg

http://img1.sycdn.imooc.com//climg/5dedcbdc09d7858106860312.jpg

同学可以先去掉这两个方法试试呢?

并且把这里也注释掉。

http://img1.sycdn.imooc.com//climg/5dedcc1009f55c8a06780171.jpg

因为老师没有同学的student,则把相关代码都注释掉了。

请同学试试,并再排查一下,看看哪里写错了。

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • 老师你好,按照你的方法做了,在我这里还是不行了,可能不是代码的问题?都报一样的错会不会是其他共有的元素的问题,刚刚依赖重新导入,缓存清空,重新编译都试过了还是出问题呢,实在不行可能要麻烦老师远程看看了
    2019-12-09 13:52:48
提问者 不停奔跑的小恐龙 2019-12-08 22:13:02
提问者 不停奔跑的小恐龙 2019-12-08 21:52:13
package com.imooc.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory=null;
     static {
         Reader reader = null;
         try {
             reader = Resources.getResourceAsReader("mybatis-config.xml");
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
         } catch (IOException e) {
             e.printStackTrace();
             throw new ExceptionInInitializerError(e);
         }

     }
         public static SqlSession openSession(){
             return sqlSessionFactory.openSession(true);
         }

         public static void closeSession(SqlSession session){
         if (session!=null){
             session.close();
             System.out.println("close执行");
         }
         }

}
H:\jdk1.8\bin\java.exe -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:55766,suspend=y,server=n -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:C:\Users\ASUS\.IntelliJIdea2019.2\system\captureAgent\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "H:\IntelliJ IDEA 2019.2.4\lib\idea_rt.jar;H:\IntelliJ IDEA 2019.2.4\plugins\junit\lib\junit-rt.jar;H:\IntelliJ IDEA 2019.2.4\plugins\junit\lib\junit5-rt.jar;H:\jdk1.8\jre\lib\charsets.jar;H:\jdk1.8\jre\lib\deploy.jar;H:\jdk1.8\jre\lib\ext\access-bridge-64.jar;H:\jdk1.8\jre\lib\ext\cldrdata.jar;H:\jdk1.8\jre\lib\ext\dnsns.jar;H:\jdk1.8\jre\lib\ext\jaccess.jar;H:\jdk1.8\jre\lib\ext\jfxrt.jar;H:\jdk1.8\jre\lib\ext\localedata.jar;H:\jdk1.8\jre\lib\ext\nashorn.jar;H:\jdk1.8\jre\lib\ext\sunec.jar;H:\jdk1.8\jre\lib\ext\sunjce_provider.jar;H:\jdk1.8\jre\lib\ext\sunmscapi.jar;H:\jdk1.8\jre\lib\ext\sunpkcs11.jar;H:\jdk1.8\jre\lib\ext\zipfs.jar;H:\jdk1.8\jre\lib\javaws.jar;H:\jdk1.8\jre\lib\jce.jar;H:\jdk1.8\jre\lib\jfr.jar;H:\jdk1.8\jre\lib\jfxswt.jar;H:\jdk1.8\jre\lib\jsse.jar;H:\jdk1.8\jre\lib\management-agent.jar;H:\jdk1.8\jre\lib\plugin.jar;H:\jdk1.8\jre\lib\resources.jar;H:\jdk1.8\jre\lib\rt.jar;H:\SXClass\mybatis\target\test-classes;H:\SXClass\mybatis\target\classes;C:\Users\ASUS\.m2\repository\org\mybatis\mybatis\3.5.1\mybatis-3.5.1.jar;C:\Users\ASUS\.m2\repository\junit\junit\4.12\junit-4.12.jar;C:\Users\ASUS\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\ASUS\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;C:\Users\ASUS\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\ASUS\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\ASUS\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.imooc.mybatis.MyBatisTestor,testManyToOne
Connected to the target VM, address: '127.0.0.1:55766', transport: 'socket'

21:41:14.024 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
21:41:14.055 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
21:41:14.056 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
21:41:14.056 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
21:41:14.056 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.



java.lang.NoClassDefFoundError: Could not initialize class com.imooc.mybatis.utils.MyBatisUtils

	at com.imooc.mybatis.MyBatisTestor.testManyToOne(MyBatisTestor.java:247)
	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:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	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)


Disconnected from the target VM, address: '127.0.0.1:55766', transport: 'socket'

Process finished with exit code -1

都在这里了

提问者 不停奔跑的小恐龙 2019-12-08 21:51:43
<?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="goodsDetail">
    <select id="selectByGoodsId" parameterType="Integer"
            resultType="com.imooc.entity.GoodsD etail">
        select * from t_goods_detail where goods_id=#{value}
    </select>
    <resultMap id="rmGoodsDetail" type="com.imooc.entity.GoodsDetail">
        <id column="gd_id" property="gdId"></id>
        <association property="goods" column="goods_id" select="goods.selectById"/>
    </resultMap>
    <select id="selectManyToOne" resultMap="rmGoodsDetail">
        select * from t_goods_detail limit 0,1
    </select>
</mapper>
<?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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/babytun?useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password"  value="123456"/>


            </dataSource>
        </environment>
        <environment id="student">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/student?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password"  value="123456"/>


            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/goods.xml"/>
        <mapper resource="mappers/student.xml"/>
        <mapper resource="mappers/goods_detail.xml"/>
    </mappers>
</configuration>
package com.imooc.mybatis;


import com.imooc.dto.GoodsDTO;
import com.imooc.entity.Goods;
import com.imooc.entity.GoodsDetail;
import com.imooc.entity.Student;
import com.imooc.mybatis.utils.MyBatisUtils;
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 org.junit.Test;

import javax.xml.ws.RequestWrapper;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.util.*;

public class MyBatisTestor {
    private Object Goods;

    @Test
    public void testSqlSessionFactory() throws IOException {
        //利用Reader加载classpath下的mybatis-config.xml核心配置文件
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        //初始化SqlSessionFactory对象,同时解析mybatis-config.xml文件
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        System.out.println("SessionFactory加载成功");

    }

    @Test
    public void testMyBatisUtils(){
        SqlSession sqlSession = null;
        try{
        sqlSession=MyBatisUtils.openSession();
        Connection connection=sqlSession.getConnection();
        System.out.println(connection);

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            MyBatisUtils.closeSession(sqlSession);
        }
    }
    @Test
    public void testSelectAll(){
        SqlSession session=null;
        try{
            session=MyBatisUtils.openSession();
            List<Goods> list=session.selectList("goods.selectAll");
            for (Goods g:list
            ) {
                System.out.println(g);
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            MyBatisUtils.closeSession(session);
        }

    }

    @Test
    public void testSelectAllStudent(){
        SqlSession session=null;
        try{
            session=MyBatisUtils.openSession();
            List<Student> list=session.selectList("student.selectAll");
            for (Student s:list
            ) {
                System.out.println(s);
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            MyBatisUtils.closeSession(session);
        }

    }

    @Test
   public void testSelectById(){
        SqlSession session=null;
        try{

            session = MyBatisUtils.openSession();
            Goods = session.selectOne("goods.selectById", 1602);
            System.out.println(Goods);
        }catch(
                Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }

    @Test
    public void selectGoodsMap(){
        SqlSession session=null;
        try{

            session = MyBatisUtils.openSession();
            List<Map> list = session.selectList("goods.selectGoodsMap");
            for (Map map : list
            ) {
                System.out.println(map);
            }
//            System.out.println(Goods);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }

    @Test
    public void selectGoodsDTO(){
        SqlSession session=null;
        try{

            session = MyBatisUtils.openSession();
            List<GoodsDTO> list = session.selectList("goods.selectGoodsDTO");
            for (GoodsDTO g : list
            ) {
                 System.out.println(g);
            }
//            System.out.println(Goods);
        }catch(Exception e){
            e.printStackTrace();
        }finally {

            MyBatisUtils.closeSession(session);
        }
    }

    @Test
    public void insert(){
        SqlSession session=null;
        try{

            session = MyBatisUtils.openSession();
            Goods goods = new Goods();
            goods.setTitle("test");
            goods.setSubTitle("test123");
            goods.setOriginalCost(200f);
            goods.setCurrentPrice(100f);
            goods.setDiscount(0.5f);
            goods.setIsFreeDelivery(1);
            goods.setCategoryId(43);
            int num=session.insert("goods.insert",goods);
            System.out.println(num);
            System.out.println(goods.getGoodsId());
            session.commit();

        }catch(Exception e){
            e.printStackTrace();
            if(session!=null){
                session.rollback();
            }
        }finally {

            MyBatisUtils.closeSession(session);
        }
    }

    @Test
    public void insertStudent(){
        SqlSession session = null;
        try {

            session=MyBatisUtils.openSession();
            Student student = new Student();
            student.setName("楠楠");
            student.setRegNo(20171208);
            student.setAge(26);
            student.setGrade("2013");
            student.setMajor("哲学系");
            student.setSex("男");
            int num = session.insert("goods.insertstudent", student);
            System.out.println(num);
            System.out.println(student.getId());
           session.commit();

        } catch (Exception e) {
            e.printStackTrace();
            if (session != null) {
                session.rollback();
            }
        }finally {
            session.close();
        }
    }

    @Test
    public void selectDynamicSql(){
        SqlSession session=null;
        List<Goods> list = new ArrayList<com.imooc.entity.Goods>();
        try{
            session = MyBatisUtils.openSession();
            Map param = new HashMap();
             param.put("categoryId", 44);
            param.put("currentPrice", 500);
            list=session.selectList("goods.dynamicSQL", param);
            for(Goods goods:list){
                System.out.println(goods);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
    }
    @Test
    public void testOneToMany(){
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            List<Goods> list = session.selectList("goods.selectOneToMany");
            for(Goods goods:list){
                System.out.println(goods.getTitle()+":"+goods.getGoodsDetails().size() );
            }
        }catch(Exception e
         ){
            e.printStackTrace();
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }
    @Test
    public void testManyToOne(){
        SqlSession session = null;
        try{
            session = MyBatisUtils.openSession();
            List<GoodsDetail> list = session.selectList("goodsDetail.selectManyToOne");
            for(GoodsDetail gd:list){
                System.out.println(gd.getGdPicUrl()+":"+gd.getGoods().getTitle() );
            }
        }catch(Exception e
        ){
            e.printStackTrace();
        }finally {
            MyBatisUtils.closeSession(session);
        }
    }

 }

j


提问者 不停奔跑的小恐龙 2019-12-08 21:48:21
<?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="goods">
    <cache eviction="LRU" flushInterval="600000" size="512" readOnly="true"/>
    <select id="selectAll" resultType="com.imooc.entity.Goods">
    select * from t_goods order by goods_id desc limit 10
    </select>

    <select id="selectById" parameterType="Integer" resultType="com.imooc.entity.Goods">
        select * from t_goods where goods_id = #{value }
    </select>

    <select id="selectGoodsMap" resultType="java.util.LinkedHashMap">
        select g.* ,c.category_name from t_goods g,t_category c
        where g.category_id= c.category_id
    </select>

    <resultMap id="rmGoods" type="com.imooc.dto.GoodsDTO">
        <id property="goods.goodsId" column="goods_id"/>
        <result property="goods.title" column="title"/>
        <result property="goods.originalCost" column="original_cost"/>
        <result property="goods.currentPrice" column="current_price"/>
        <result property="goods.discount" column="discount"/>
        <result property="goods.isFreeDelivery" column="is_free_delivery"/>
        <result property="goods.categoryId" column="category_id"/>
        <result property="category.categoryId" column="category_id"/>
        <result property="category.categoryName" column="category_name"/>
        <result property="category.parentId" column="parent_id"/>
        <result property="category.categoryLevel" column="category_levele"/>
        <result property="category.categoryOrder" column="category_order"/>
        <result property="test" column="test"/>
    </resultMap>
    <select id="selectGoodsDTO" resultMap="rmGoods">
        select g.* ,c.* , '1' as test from t_goods g,t_category c
        where g.category_id= c.category_id
    </select>
    
    <insert id="insert" parameterType="com.imooc.entity.Goods">
       INSERT INTO t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)
         VALUES (#{title} , #{subTitle} , #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})
    <selectKey resultType="Integer" keyProperty="goodsId" order="AFTER">
        select last_insert_id()
    </selectKey>
    </insert>

    <insert id="insertstudent" parameterType="com.imooc.entity.Student"
    keyProperty="id" keyColumn="id" useGeneratedKeys="true">

        INSERT INTO student(reg_no,name,sex,age,grade,major)
        VALUES(#{regNo},#{name},#{sex},#{age},#{grade},#{major})
<!--        <selectKey resultType="Integer" keyProperty="id" order="AFTER">-->
<!--            SELECT last_insert_id()-->
<!--        </selectKey>-->

    </insert>
    
    <select id="dynamicSQL" parameterType="java.util.Map" resultType="com.imooc.entity.Goods">
        select * from t_goods
      <where>
        <if test="categoryId != null">
            and category_id = #{categoryId}
        </if>
        <if test="currentPrice != null">
            and current_price &lt; #{currentPrice}
        </if>
      </where>
    </select>

    <select id="dynamicStu" parameterType="java.util.Map" resultType="com.imooc.entity.Student">
        select * from student
        <where>
            <if test="age !=null">
                and age &lt; #{age}
            </if>
            <if test="sex !=null">
                and sex = #{sex}
            </if>
        </where>
        order by id desc
    </select>

    <resultMap id="rmGoods1" type="com.imooc.entity.Goods">
        <id column="goods_id" property="goodsId"></id>
        <collection property="goodsDetails" select="goodsDetail.selectByGoodsId"
                    column="goods_id"/>

    </resultMap>
    <select id="selectOneToMany" resultMap="rmGoods1" >
        select * from t_goods limit 0,10
    </select>

</mapper>


好帮手慕阿莹 2019-12-08 17:19:27

同学你好,建议同学清除一下缓存并重启eclipse再试试呢?

http://img1.sycdn.imooc.com//climg/5decbfd009d3868c02160227.jpg

如果是idea

http://img1.sycdn.imooc.com//climg/5decbfee09e9fab803350215.jpg

如果还是不行,请再次提问,另外,同学今天是修改了哪些呢?去掉今天修改的部分,是否还会报错呢?

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • 我没有修改什么,只是新写了新的内容,运行不成功之后,我测试昨天写好的方法,也报错了,一样的错误
    2019-12-08 18:50:45
  • 重建项目重启也还是不行
    2019-12-08 18:51:14
  • 同学你好,从同学贴的代码来看,粘到老师的代码中,是可以运行的,请同学把全部代码再贴一下,包括项目的目录结构,因为老师的GoodsDetail在com.imooc.mybatis.entity包中,同学的是否是在com.imooc.entity中呢? 另外,老师的命名空间写的是goodsDetail,同学写的是goods_detail吗? 注意不要贴在回复里,会失去代码的格式。可以在“我要回答”里贴一下。祝学习愉快。
    2019-12-08 19:29:02
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师