hibernate實現分表後擷取insert自增ID方法。

來源:互聯網
上載者:User

標籤:hibernate

#第一種基於原生的JDBC的方式實現

private Integer insert(POJO entity, String table) throws SQLException {String insertSQL = "INSERT INTO " + table + " (XXXX)VALUES(?,?,?,?,?,?,?,?)";DataSource dataSource = SessionFactoryUtils.getDataSource(getHibernateTemplate().getSessionFactory());Connection connection = null;PreparedStatement pStatement = null;ResultSet resultSet = null;try {connection = dataSource.getConnection();pStatement = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);pStatement.setInt(1, entity.getSId());pStatement.setInt(2, entity.getNum());pStatement.executeUpdate();resultSet = pStatement.getGeneratedKeys();if (resultSet.next()) {return resultSet.getInt(1);}} finally {if (resultSet != null) {resultSet.close();resultSet = null;}if (pStatement != null) {pStatement.close();pStatement = null;}if (connection != null) {connection.close();connection = null;}}return -1;}


#第二種 使用基於原生的Hibernate實現

import java.util.Date;import org.hibernate.Session;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.orm.hibernate3.HibernateTemplate;import org.springframework.stereotype.Component;@Componentpublic class TestDAO {@Autowired@Qualifier("XXXXTemplate")private HibernateTemplate template;private SQLInterceptor interceptor = new SQLInterceptor("tableName");public void save(POJO entity){Session session = template.getSessionFactory().openSession(interceptor);/*分表策略:按月份對資料進行分割*/Integer yearMonth = Integer.parseInt(DateUtils.format(new Date(), "yyyyMM"));interceptor.setNewTable("tableName_"+yearMonth);session.save(entity);session.close();System.out.println("返回主鍵ID:" + entity.getId());}}
#HibernateSQL攔截器

import org.hibernate.EmptyInterceptor;public class SQLInterceptor extends EmptyInterceptor {private static final long serialVersionUID = 1637672155224242981L;public SQLInterceptor(String table) {this.table = table;}public String table;private String newTable;public void setNewTable(String newTable) {this.newTable = newTable;}@Overridepublic String onPrepareStatement(String sql) {if (StringUtils.isNotEmpty(table, newTable)) {sql = sql.replaceAll(table, newTable);}return super.onPrepareStatement(sql);}}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.