JdbcTemplate与JPA查询

时间:2015-12-01 15:14:25

标签: spring jdbc spring-data spring-data-jpa jdbctemplate

我面临奇怪的问题,其中SAME查询通过jdbctemplate.queryForList工作,但不能通过JpaRepository @Query工作。 jdbctemplate和jpa entityManagerFactory + transactionManager都使用相同的数据源,连接到SQL Server。 当jpa查询运行时返回:SQL错误:942,SQLState:42000; ORA-00942:表或视图不存在。 Jdbctemplate查询返回数据库中的数据。

config xml:

<bean id="dataSourceSQL" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
    <property name="url" value="jdbc:sqlserver://host:1433;databaseName=SQLServerName"/>
    <property name="username" value="***"/>
    <property name="password" value="***"/>
</bean>

<bean id="jdbcTemplateSQL" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource"  ref="dataSourceSQL" />
</bean>

<bean id="entityManagerFactorySQL" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSourceSQL">
</bean>

<bean id="transactionManagerSQL" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactorySQL" />
</bean>

<tx:annotation-driven transaction-manager="transactionManagerSQL" />

Repository.java

@Transactional(propagation=Propagation.MANDATORY, value="transactionManagerSQL") 
public interface Repository extends JpaRepository<Users, Long>{
@Query(nativeQuery=true, value="select u.name from schema.Users u")
List<String> findUsers();
}

Test.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath*:spring/config.xml" })
@TransactionConfiguration(transactionManager = "transactionManagerSQL",    defaultRollback = true)

public class Test {
@Autowired Repository repository;
@Autowired JdbcTemplate jdbcTemplateSQL;

@Test
@Transactional("transactionManagerSQL")
public void testJpa() {
     List<String> records = repository.findUsers(); //fails with table not found exception
     assertNotNull(records);
}

@Test
public void testJdbcTemplate(){
    List<Map<String, Object>> records=jdbcTemplateSQL.queryForList("select u.name from schema.Users u"); //returns results
    assertNotNull(records);
}
}

0 个答案:

没有答案