---
title: "Spring中获得数据库的自增主键值"
author: "lxsgoodluck"
date: "2009-04-04T10:13:35Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2009-04-04T10:15:26Z"
id: 361348
url: "https://webwork.iteye.com/blog/361348"
---

```java
...
	class Insert extends SqlUpdate {

		private final Logger logger = Logger.getLogger(Insert.class);

		public Insert(DataSource dataSource) {
			super(dataSource, INSERT_SQL);
			initInsertParams(this);  //初始化insert参数,与此处没有直接关系
			
			this.setReturnGeneratedKeys(true);  //设置可以返回主键信息
			
			if(logger.isDebugEnabled())
				logger.debug(" sql =" + this.getSql());
		}
	}

	private Insert insert;

	private synchronized void insert(Object obj) {
		Object[] values = getInsertValues(obj);
		
		//返回的主键信息将保存在GeneratedKeyHolder的LinkedList中
		KeyHolder keyHolder = new GeneratedKeyHolder();
		this.insert.update(values, keyHolder);
		
		((ObjectId) obj).setId(keyHolder.getKey().longValue());
	}
...
```

以上是AbstractDao的部分代码，提醒的一点是：如果在Spring中使用获取最新自增主键值的查询语句，比如MySQL的SELECT LAST_INSERT_ID()时，一定要注意SELECT LAST_INSERT_ID()是真对当前insert或update的Connection的，而Spring中每次操作是如此获得Connection的【Connection con = DataSourceUtils.getConnection(getDataSource());】，所以如果不能正确使用会得不到自己想要的结果。