我使用JDBC批量插入插入许多记录.有没有办法获得每条记录的生成密钥?我可以使用ps.getGeneratedKeys()批量插入吗?
我在用 oracle.jdbc.OracleDriver
final String insert = "Insert into Student(RollNumber, Name, Age) values(StudentSEQ.nextval, ? , ?)";
final int BATCH_SIZE = 998;
int count = 0;
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
ps = con.prepareStatement(insert);
for (Student s : students) {
ps.setString(1, s.getName());
ps.setInt(2, s.getAge());
ps.addBatch();
count++;
if (count % BATCH_SIZE == 0) {
// Insert records in batches
ps.executeBatch();
}
}
// Insert remaining records
ps.executeBatch();
} finally {
if(ps != …Run Code Online (Sandbox Code Playgroud) 我必须使用hibernate将大量对象保存到数据库中.我想在会话中出现n(BATCH_SIZE)对象时提交,而不是一次提交所有这些对象.
Session session = getSession();
session.setCacheMode(CacheMode.IGNORE);
for(int i=0;i<objects.length;i++){
session.save(objects[i]);
if( (i+1) % BATCH_SIZE == 0){
session.flush();
session.clear();
}
}
Run Code Online (Sandbox Code Playgroud)
我会尝试类似上面的东西,但我读到session.flush()它没有提交数据库的更改.这是以下代码正确的方法吗?
Session session = getSession();
session.setFlushMode(FlushMode.COMMIT);
session.setCacheMode(CacheMode.IGNORE);
session.beginTransaction();
for(int i=0;i<objects.length;i++){
session.save(objects[i]);
if( (i+1) % BATCH_SIZE == 0){
session.getTransaction().commit();
session.clear();
//should I begin a new transaction for next batch of objects?
session.beginTransaction();
}
}
session.getTransaction().commit();
Run Code Online (Sandbox Code Playgroud) 我是否需要手动关闭从休眠会话中获得的连接?
如果我这样做,我会关闭连接池中的一个连接吗?
如果我不这样做,休眠会自动关闭连接吗?
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "sql query";
try {
Session session = this.sessionFactory.getCurrentSession();
con = session.connection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
//read result set
}
} catch (SQLException exp) {
log.error("Error: ", exp);
} finally{
if(ps != null)
ps.close();
if(con != null)
con.close(); //Is this required?
}
Run Code Online (Sandbox Code Playgroud) 我有一个阵列
String[] grades = new String[]{"D","C-","C","C+","B-","B","B+","A-","A","A+"};
Run Code Online (Sandbox Code Playgroud)
我想检查字符串是否是这些值之一.
我可以遍历数组来实现这一目标,但我希望通过正则表达式完成.
java ×4
batch-insert ×2
hibernate ×2
commit ×1
flush ×1
jdbc ×1
oracle ×1
primary-key ×1
regex ×1