具有相同列名的命名查询内部联接表的重复数据/值

ttygqcqt  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(364)

我尝试使用下面的命名查询连接三个表:student、borrowedbook和books

List< Student > stuList= new ArrayList< Student >( );
StringBuilder sb = new StringBuilder( );
sb.append( "select s.studentId, s.name, s.lastName, b.name " );
sb.append( "from student s " );
sb.append( "inner join borrowedbook c on 
            s.studentId = c.studentId " );
sb.append( "inner join books b on c.bookId = b.bookId " );

Query query = getSession( ).createSQLQuery( sb.toString( ) );
query.setProperties( Student.class );

List< Object[] > searchResults = query.list( );

但是,当我在调试模式的searchresults中检查b.name的值时,它会得到s.name的值。意思是,b.name和s.name的名字是一样的,尽管它应该有自己的名字。我不知道这里有什么问题,我甚至给了他们一个别名来区分他们。

i7uaboj4

i7uaboj41#

你应该给他们取个别名 name 不同内容的列:

StringBuilder sb = new StringBuilder( );
sb.append( "select s.studentId, s.name as student_name, s.lastName, " );
sb.append( " b.name as book_name " );
sb.append( "from student s " );
sb.append( "inner join borrowedbook c on s.studentId = c.studentId " );
sb.append( "inner join books b on c.bookId = b.bookId " );

然后使用列名访问结果集 student_name 以及 book_name .

相关问题