iT邦幫忙

0

有關SpringBoot-JdbcTemplate報錯TransientDataAccessResourceException...

C 2022-02-19 11:50:13777 瀏覽
  • 分享至 

  • xImage

環境

  • Java 版本:OpenJDK 11
  • 資料庫:MySQL 8.0.23
  • 構建工具:Maven 3.6.3
  • 需求:開發 Web API

**Dependenies:

  • devtools 2.6.3
  • lombok 1.18.22
  • mysql-connector-java 8.0.28
  • spring-boot-starter-web 2.6.3
  • spring-boot-starter-jdbc 2.6.3

實體類別

@Getter
@Setter
@ToString
public class AuthorityEntity extends Base{
	
	private int id;
	private String name;
}

繼承類別

@Getter
@Setter
public class Base {
	
	private String crUser;
	private LocalDateTime crDateTime;
    private String upUser;
    private LocalDateTime upDateTime;
    
}

持久層

public interface AuthorityDao {
    public int updateAuthority(AuthorityEntity authority);
}

實作代碼

@Repository
public class AuthorityImp implements AuthorityDao {
    
    @Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private JdbcTemplate jdbcNameTemplate;

    public int updateAuthority(AuthorityEntity authority) {
		String sql = " UPDATE deploy_authority "
					+ " SET NAME = :name, UPDATE_TIME = :upDateTime ,UPDATE_USER = :upUser"
					+ " WHERE ID = :id ";

		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(authority);
		
		return jdbcNameTemplate.update(sql, paramSource);
	}

測試代碼

@SpringBootTest
class AuthorityDaoTest {

	@Autowired
	AuthorityDao authorityDao;
    
    @Test
	public void updateAuthority() {
		try {

			AuthorityEntity authority = new AuthorityEntity();
			authority.setId(1);
			authority.setName("newname");
			authority.setUpDateTime(LocalDateTime.now());
			authority.setUpUser("upuser");
			Integer result = authorityDao.updateAuthority(authority);
			System.out.println("更新成功:id為" + result);
		} catch (Exception e) {
			System.out.println("更新失敗");
			System.out.println(e);
		}
	}

}

代碼有些雜,首次po這類問題,有需要改進地方請見諒。

在做Junit5測試時,會通過CRUD測試,但Insert,Update資料時卻會報錯
org.springframework.dao.TransientDataAccessResourceException:PreparedStatementCallback;

導致資料庫實際不會有Insert,Update的資料,檢查其他類別也是同樣結構卻不報錯。

找了一段時間實在沒辦法,來版上求助各位大神....ORZ

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
喵凹咿唉思嗯
iT邦研究生 5 級 ‧ 2022-02-22 10:23:29
最佳解答

不知道您這邊指的CRUD沒問題是指什麼.. 如果Insert/Update都能通過測試 應該不會有這邊的Update問題呀XD

簡單試了一下您提供的程式, 不知道您遇到的錯誤訊息是不是

Parameter index out of range (1 > number of parameters, which is 0)

簡單查一下就會發現這個問題其實是來自於SQL的Template, 在系統要幫您代換變數時發現找不到可以代換用的"?", 譬如說像這篇就有簡單的說明

您可能會疑問這邊用的明明是Spring要自動幫您代換變數名稱才對, 但實際上是, 您變數的宣告並不與您要的功能相匹配

@Autowired
private JdbcTemplate jdbcNameTemplate;

宣告改為

@Autowired
private NamedParameterJdbcTemplate jdbcNameTemplate;

應該就能正確的往後走

另外, Spring有提供Spring data JPA可以使用, 也有更好用的"魔法", 可以參考看看其他的教學文章, 資料操作起來會更簡單

C iT邦新手 4 級 ‧ 2022-02-23 01:21:42 檢舉

感謝您的熱心回答,經你一說我才發現自己犯了低俗錯誤...

https://ithelp.ithome.com.tw/upload/images/20220223/201241971O0VsChdbF.png

我要發表回答

立即登入回答