MyBatis select语句返回空值

时间:2012-12-18 15:50:44

标签: jdbc mybatis

我正在尝试运行一个简单的MyBatis示例,从“train”表中选择所有行。

问题在于查询执行,但它返回一个列表,其中包含正确数量的元素,但填充了空值。 直接使用JDBC PreparedStatement运行的相同查询工作正常。

也许这是一个配置问题,但我无法弄清楚我做错了什么。

这是代码。提前谢谢。

Train.java

package org.example.mybatis.domain;

public class Train implements Serializable
{
private int id;
private String type;

    // getters and setters
}

TrainMapper.java

package org.example.mybatis.persistence;

public interface TrainMapper {

List<Train> getAllTrains();
}

TrainSelector.java

package org.example.mybatis.test;

public class TrainSelector implements TrainMapper {

    private static String resource = "mybatis-config.xml";
    private static SqlSessionFactory factory = null;

    private SqlSessionFactory getSqlSessionFactory()
    {
        if (factory == null)
        {
            try {
                InputStream inputStream = Resources.getResourceAsStream(resource);
                factory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
         }
         return factory;
    }

    @Override
    public List<Train> getAllTrains()
    {
        List<Train> trains = null;

        SqlSession session = getSqlSessionFactory().openSession();
        try {
            TrainMapper mapper = session.getMapper(TrainMapper.class);
            trains = mapper.getAllTrains();
        } finally {
            session.close();
        }   
        return trains;
    }

    public static void main(String[] args) {
        List<Train> trains = null;

        TrainSelector trainSelector = new TrainSelector();
        trains = trainSelector.getAllTrains();

        System.out.println(trains);
    }

}

的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>
  <properties resource="database.properties" />

  <typeAliases>
    <typeAlias alias="Train" type="org.example.mybatis.domain.Train" />
    <!--package name="org.example.mybatis.domain" />-->
  </typeAliases>

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED">
        <property name="driver" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" />
      </dataSource>
    </environment>
  </environments>

  <mappers>
    <mapper resource="org/example/mybatis/persistence/TrainMapper.xml" />
  </mappers>
</configuration>

TrainMapper.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="org.example.mybatis.persistence.TrainMapper">

  <cache />

  <select id="getAllTrains" parameterType="list" resultType="Train">
    SELECT * 
    FROM trains
  </select>
</mapper>

JdbcStatementExample.java

package org.example.mybatis.test;

public class JdbcStatementExample {

    private static void selectAllTrains() throws SQLException
    {
        String sql = "SELECT * FROM trains";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://localhost/testing";
        String user = "test";
        String password = "test";

        try {
            conn = DriverManager.getConnection(url, user, password);
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                String id = rs.getString("train_id");
                String type = rs.getString("train_type");
                System.out.println("id: " + id);
                System.out.println("type: " + type);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
    }

    public static void main(String[] args)
    {
        try {
            selectAllTrains();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

3 个答案:

答案 0 :(得分:4)

结果集中列的名称与Train对象中的属性名称不同。您需要一个显式的结果映射,让Mybatis知道哪个列要映射到哪个属性。

<resultMap id="trainMap" type="Train>
        <id property="id" column="train_id" javaType="java.lang.Integer" jdbcType="INTEGER"/>
        <result property="type" column="train_type" javaType="java.lang.String" jdbcType="VARCHAR"/>
</resultMap>

将您的选择元素设为

<select id="getAllTrains" parameterType="list" resultType="trainMap">
    SELECT * FROM trains
</select>

答案 1 :(得分:0)

其他选项是使用列名作为别名。

列名称将是数据库的名称,别名将设置为与Train对象的属性相匹配:

<select id="getAllTrains" parameterType="list" resultType="trainMap">
  SELECT 
  train_id as id,
  train_type as type
  FROM trains
</select>

答案 2 :(得分:0)

结果可以按照 Seeta 的描述或在此处的官方文档中进行映射: https://mybatis.org/mybatis-3/sqlmap-xml.html

在 MyBatis 3.x 中,示例不起作用,因为您需要设置 resultMap 而不是 resultType。并且您不能同时设置两者!工作示例如下所示:

<select id="getAllTrains" parameterType="list" resultMap="trainMap">
    SELECT * FROM trains
</select>