关于
executeupdate()的搜索结果
问题
JFinal 1.4 druid 0.2.26 model.save()保存怪事?报错
//方法1,用model.save()方式。
private void saveClickNum(Integer type,Long click_pkid,Integer click_num){
…
爱吃鱼的程序员
2020-06-22 16:49:05
0 浏览量
回答数 1
回答
public class DataBase {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public DataBase() {
// oracle 的jdbc 连接
try {
OracleDataSource ds = new OracleDataSource();
ds.setUser(“uamqas02”);
ds.setPassword(“uamqas02”);
ds.setURL(“jdbc:oracle:thin:@localhost:1521:devdb01”);
conn = ds.getConnection();
stmt = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql) {
rs = null;
try {
// stmt=conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
System.err.println(“executeQuerty:” e.getMessage());
}
return rs;
}
// —————————数据库的更新、修改、删除操作————————————————-
public boolean executeUpdate(String sql) // 更新方法(增、删、改)
{
boolean temp = false;
try {
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
if (i >= 1)
temp = true;
} catch (SQLException e) {
e.printStackTrace();
System.err.println(“executeUpdate:” e.getMessage());
}
return temp;
}
public boolean saveOrUpdateCommit(String sql, String sql2) {
boolean temp = true;
try {
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.addBatch(sql);
stmt.addBatch(sql2);
stmt.executeBatch();
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
temp = false;
// 回滚
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
temp = false;
e.printStackTrace();
}
return temp;
}
public void closeStmt() {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeConn() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
蛮大人123
2019-12-02 01:57:48
0 浏览量
回答数 0
回答
query.executeUpdate()也可以执行原生的插入语句。Query query = em.createNativeQuery(“insert into table(column1,column2) values (), (),()”);query.executeUpdate();
小旋风柴进
2019-12-02 01:57:24
0 浏览量
回答数 0
万券齐发助力企业上云,爆款产品低至2.2折起!
限量神券最高减1000,抢完即止!云服务器ECS新用户首购低至0.95折!
回答
第一种Python如果你是用类似sqlalchemy这样的orm数据库
def upload_blob(file_data):
fb = StringIO.StringIO()
file_data.save(fb)
filename = file_data.filename
c_blob_id = None
if filename:
blob = T_Blob()
blob.c_filename = filename
blob.c_blob = fb.getvalue()
db.session.add(blob)
db.session.flush()
c_blob_id = blob.id
return c_blob_id
调用
form = AddFileForm()
if form.validate_on_submit():
user = g.user
c_blob_id = models.upload_blob(form.c_fj.data)
第二种 java jdbc方式插入Oracle
import java.sql.*;
import java.io.*;
import oracle.sql.*;
public class IntoOracle {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = OracleFactory.getOracle();
conn.setAutoCommit(false);
BLOB blob = null;
PreparedStatement pstmt = conn.prepareStatement(“insert into blobtest(id,b) values(?,empty_blob())”);
pstmt.setString(1,”50″);
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement(“select b from blobtest where id= ? for update”);
pstmt.setString(1,”50″);
ResultSet rset = pstmt.executeQuery();
if (rset.next()) blob = (BLOB) rset.getBlob(1);
String fileName = “d:\bjx.jpg”;
File f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
System.out.println(“file size = ” fin.available());
pstmt = conn.prepareStatement(“update blobtest set b=? where id=?”);
OutputStream ut = blob.getBinaryOutputStream();
int count = -1, total = 0;
byte[] data = new byte[(int)fin.available()];
fin.read(data);
out.write(data);
fin.close();
out.close();
pstmt.setBlob(1,blob);
pstmt.setString(2,”50″);
pstmt.executeUpdate();
pstmt.close();
conn.commit();
conn.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Exception e){
e.printStackTrace();
}
}
}
a123456678
2019-12-02 03:03:16
0 浏览量
回答数 0
回答
第一种Python如果你是用类似sqlalchemy这样的orm数据库
def upload_blob(file_data):
fb = StringIO.StringIO()
file_data.save(fb)
filename = file_data.filename
c_blob_id = None
if filename:
blob = T_Blob()
blob.c_filename = filename
blob.c_blob = fb.getvalue()
db.session.add(blob)
db.session.flush()
c_blob_id = blob.id
return c_blob_id
调用
form = AddFileForm()
if form.validate_on_submit():
user = g.user
c_blob_id = models.upload_blob(form.c_fj.data)
第二种 java jdbc方式插入Oracle
import java.sql.*;
import java.io.*;
import oracle.sql.*;
public class IntoOracle {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = OracleFactory.getOracle();
conn.setAutoCommit(false);
BLOB blob = null;
PreparedStatement pstmt = conn.prepareStatement(“insert into blobtest(id,b) values(?,empty_blob())”);
pstmt.setString(1,”50″);
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement(“select b from blobtest where id= ? for update”);
pstmt.setString(1,”50″);
ResultSet rset = pstmt.executeQuery();
if (rset.next()) blob = (BLOB) rset.getBlob(1);
String fileName = “d:\bjx.jpg”;
File f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
System.out.println(“file size = ” fin.available());
pstmt = conn.prepareStatement(“update blobtest set b=? where id=?”);
OutputStream ut = blob.getBinaryOutputStream();
int count = -1, total = 0;
byte[] data = new byte[(int)fin.available()];
fin.read(data);
out.write(data);
fin.close();
out.close();
pstmt.setBlob(1,blob);
pstmt.setString(2,”50″);
pstmt.executeUpdate();
pstmt.close();
conn.commit();
conn.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Exception e){
e.printStackTrace();
}
}
}
以上
a123456678
2019-12-02 03:00:39
0 浏览量
回答数 0
问题
java 怎么多表同时插入到数据库啊?报错
“
public class Add { public void add(String fid,String title,String content){ Connection connection = null; Stat…
因为相信,所以看见。
2020-05-27 10:02:53
8 浏览量
回答数 1
回答
1.去网站下载sqlitejdbc.根据自已需要,下载sqlitejdbc.(sqlitejdbc有两个版本,一种是pure的一种是native的。native的速度快。它放在**-bin.tgz里。我下的就是这种sqlitejdbc-v056-bin.tgz)
下载后解压sqlitejdbc-v056-bin.tg ,有以下几个文件: libsqlitejdbc.so,sqlitejdbc.dll,libsqlitejdbc.jnilib,sqlitejdbc-v056-native.jar。
其中libsqlitejdbc.so是linux下的动态链接库,sqlitejdbc.dll是windows下的动态链接库, libsqlitejdbc.jnilib是Mac下的动态链接库。
3.根据自已的操作系统将sqlitejdbc-v056-native.jar与对应动态链接库放到jdk/jre/lib/ext里。(我的是linux,则将sqlitejdbc-v056-native.jar 与libsqlitejdbc.so 放到jdk/jre/lib/ext中)。
3.如果你只是随便的将sqlitejdbc.jar放在任一目录,并且你又是run in pure-java mode(纯java模式下运行?是这么译吗)请参考https://bitbucket.org/xerial/sqlite-jdbc
4.如果你已看了第三步的网站,以下可以不用看了,下面的介绍只是复述3里面的而已。
5.http://www.xerial.org/trac/Xerial/wiki/SQLiteJDBC 的实例经验证可以运行。
public class Sample
{
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName(“org.sqlite.JDBC”);
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(“jdbc:sqlite:sample.db”);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate(“drop table if exists person”);
statement.executeUpdate(“create table person (id integer, name string)”);
statement.executeUpdate(“insert into person values(1, ‘leo’)”);
statement.executeUpdate(“insert into person values(2, ‘yui’)”);
ResultSet rs = statement.executeQuery(“select * from person”);
while(rs.next())
{
// read the result set
System.out.println(“name = ” rs.getString(“name”));
System.out.println(“id = ” rs.getInt(“id”));
}
}
catch(SQLException e)
{
// if the error message is “out of memory”,
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
蛮大人123
2019-12-02 01:53:02
0 浏览量
回答数 0
回答
String sql=”update emp set ?=? where empno=? “;
try
{
ps=conn.prepareStatement(sql);
ps.setString(1,oldInfo);
ps.setInt(2, infoInt);
ps.setInt(3,empId);
count=ps.executeUpdate();
}
字段不能通过参数方式,改成
String sql=”update emp set “ oldInfo “=? where empno=? “;
try
{
ps=conn.prepareStatement(sql);
ps.setInt(1, infoInt);
ps.setInt(2,empId);
count=ps.executeUpdate();
}
蛮大人123
2019-12-02 02:09:48
0 浏览量
回答数 0
问题
Spring3 hibernate3 在dao层使用Query的executeUpdate不回滚
Dao层@Overridepublic int updateRetrailState(Integer orsa_id, int srcState, int targetState, String userName) { String hql…
a123456678
2019-12-01 20:23:58
998 浏览量
回答数 1
问题
jdbc连接mysql后数据插不进去,什么问题?
public class test {
public static void main(String[] args) {
try {
String info…
落地花开啦
2019-12-01 20:01:46
1230 浏览量
回答数 2
回答
rs=preStmt.executeUpdate(sql);这句改成rs=preStmt.executeUpdate();executeUpdate(String SQL)执行的静态的SQL语句,其实你是执行了INSERT INTO hr_role (nc_id,name) values (?,?),就抛出了mysql 语法错误
蛮大人123
2019-12-02 01:53:44
0 浏览量
回答数 0
回答
快照版本这里:http://code.alibabatech.com/mvn/snapshots/com/alibaba/druid/0.2.16-SNAPSHOT
我测试过,问题已经解决了。正式版本下个星期发布。十分感谢!这是postgres-styletypecast表达式,你提问之后,我查文档才懂。下个星期发布版本解决此问题。
createtableTUSER(IDvarchar(36)notnull,CREATEDATETIMEdatetime,MODIFYDATETIMEdatetime,NAMEvarchar(100)notnull,PWDvarchar(32)notnull,primarykey(ID))com.alibaba.druid.sql.parser.ParserException:TODOatcom.alibaba.druid.sql.parser.SQLExprParser.parsePrimaryKey(SQLExprParser.java:1298)atcom.alibaba.druid.sql.parser.SQLCreateTableParser.parseCrateTable(SQLCreateTableParser.java:75)atcom.alibaba.druid.sql.parser.SQLStatementParser.parseCreate(SQLStatementParser.java:556)atcom.alibaba.druid.sql.parser.SQLStatementParser.parseStatementList(SQLStatementParser.java:102)atcom.alibaba.druid.sql.parser.SQLStatementParser.parseStatementList(SQLStatementParser.java:76)atcom.alibaba.druid.sql.visitor.ParameterizedOutputVisitorUtils.parameterize(ParameterizedOutputVisitorUtils.java:42)atcom.alibaba.druid.filter.stat.StatFilter.mergeSql(StatFilter.java:145)atcom.alibaba.druid.filter.stat.StatFilter.createSqlStat(StatFilter.java:629)atcom.alibaba.druid.filter.stat.StatFilter.internalBeforeStatementExecute(StatFilter.java:397)atcom.alibaba.druid.filter.stat.StatFilter.statementExecuteUpdateBefore(StatFilter.java:325)atcom.alibaba.druid.filter.FilterEventAdapter.statement_executeUpdate(FilterEventAdapter.java:324)atcom.alibaba.druid.filter.FilterChainImpl.statement_executeUpdate(FilterChainImpl.java:2373)atcom.alibaba.druid.proxy.jdbc.StatementProxyImpl.executeUpdate(StatementProxyImpl.java:225)atcom.alibaba.druid.pool.DruidPooledStatement.executeUpdate(DruidPooledStatement.java:169)atorg.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:227)atorg.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:178)atorg.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:505)atorg.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1769)atorg.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)atorg.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:242)atorg.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:372)atorg.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:357)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)atorg.springframework.beans.factory.support.AbstractBeanFactory1.getObject(AbstractBeanFactory.java:294)atorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)atorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)atorg.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)atorg.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:591)atorg.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)atorg.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)atorg.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)atorg.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)atorg.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)atorg.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)atorg.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)atorg.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)atorg.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)atorg.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)atorg.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)atorg.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1113)atorg.apache.catalina.startup.HostConfigDeployDirectory.run(HostConfig.java:1671)atjava.util.concurrent.ExecutorsRunnableAdapter.call(Executors.java:441)atjava.util.concurrent.FutureTaskSync.innerRun(FutureTask.java:303)atjava.util.concurrent.FutureTask.run(FutureTask.java:138)atjava.util.concurrent.ThreadPoolExecutorWorker.runTask(ThreadPoolExecutor.java:885)atjava.util.concurrent.ThreadPoolExecutorWorker.run(ThreadPoolExecutor.java:907)atjava.lang.Thread.run(Thread.java:619)
sqlserver也报错啊
爱吃鱼的程序员
2020-06-22 20:42:32
0 浏览量
回答数 0
问题
javaweb工程的一个功能无法实现请求帮忙
在写一个类似于校园图书馆的网页工程,在还书功能那里遇到麻烦了用的是mysql5.6 myeclipse10 其他功能都运行良好在DAO层/还书/
public void backBook(int bkid, int stid) throws…
a123456678
2019-12-01 20:15:35
820 浏览量
回答数 1
问题
mysql 插入繁体字报错?报错
@jfinal程序插入繁体字mysql的时候报错,数据库设置了utf8,但是依然报错,数据库,表,字段,都设置了utf8。请问大家有什么办法吗
…
爱吃鱼的程序员
2020-06-22 14:09:16
0 浏览量
回答数 1
问题
省略的catch方法应该怎么写?
public class UsersDAO { private Connection con; private PreparedStatement pt; private ResultSet rs; public boolean findU…
蛮大人123
2019-12-01 20:01:36
969 浏览量
回答数 1
问题
有没有办法从准备好的语句中检索自动增量ID?mysql
使用带有预准备语句的Java查询时,是否有一种方法可以从数据库查询中检索自动生成的键。
例如,我知道AutoGeneratedKeys可以按以下方式工作。
stmt = conn.createStat…
保持可爱mmm
2020-05-17 10:05:44
1 浏览量
回答数 1
问题
向mysql数据库中插入数据时报错的问题
下面是我的代码
public class categorydao {
public static void save(category c) throws SQLException{
Connection conn=…
落地花开啦
2019-12-01 19:47:44
2300 浏览量
回答数 3
问题
dbcp 导致oracle存在很多incative session
往oracle数据库里插入数据,Connection 是从DBCP里拿到的,在插入后对Connection和PreparedStament都有作finally{.close()}处理,但是发现oracle中v$session 存在很多ina…
蛮大人123
2019-12-01 19:54:34
1363 浏览量
回答数 1
回答
`connection.setAutoCommit(false); stmt = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); stmt.executeUpdate(); ResultSet keys = stmt.getGeneratedKeys(); if(keys.next()){key = keys.getLong(1);} connection.commit();`
落地花开啦
2019-12-02 01:44:15
0 浏览量
回答数 0
问题
将截断字符串或二进制数据问题
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb1){
Connection ct=null;
Statement stm=null;
PreparedSt…
蛮大人123
2019-12-01 19:36:20
1941 浏览量
回答数 1
问题
更新ORACLE数据库DATE类型的字段时报错:报错
@JFinal 你好,想跟你请教个问题:
Jfinal通过Druid操作Oracle数据库,更新日期类型(DATE类型)的字段失败以下是代码
Test test…
kun坤
2020-06-20 13:28:20
1 浏览量
回答数 1
问题
更新ORACLE数据库DATE类型的字段时报错?报错
@JFinal 你好,想跟你请教个问题:
Jfinal通过Druid操作Oracle数据库,更新日期类型(DATE类型)的字段失败以下是代码
Test test…
爱吃鱼的程序员
2020-06-12 10:31:34
0 浏览量
回答数 1
问题
更新ORACLE数据库DATE类型的字段时报错 配置报错
@JFinal 你好,想跟你请教个问题: Jfinal通过Druid操作Oracle数据库,更新日期类型(DATE类型)的字段失败以下是代码
Test test= Test…
kun坤
2020-05-30 23:33:31
0 浏览量
回答数 1
问题
关于 Hibernate 中 update 不执行,不报错 求解!
最近调试的时候,发现 之前写好的 项目出了问题。
就是在执行 update、delete 的时候, 不执行,但是也不报错。
配置输出 SQL语句的时候,看不到 SQL语句。数据库中也没有任何变化。
爬文了两天没有结果, 但是发现 如果使…
爵霸
2019-12-01 20:06:20
1626 浏览量
回答数 1
问题
我从txt文本中读取中文文本然后存到mysql数据库中,中文变成了乱码!
public static void JD() throws IOException{
File input =new File(“/Users/huboqin/Downloads/网页1/京东/jd450.html”);
…
爵霸
2019-12-01 19:54:27
1013 浏览量
回答数 1
问题
jdbc报错
PreparedStatement preStmt=null;
int rs=0;
String sql = “INSERT INTO hr_role (nc_id,name) values (?,?)”; …
蛮大人123
2019-12-01 20:02:15
995 浏览量
回答数 1
问题
java的DriverManager.getConnection返回同一个connection报错
我启动了十个线程去测试一个业务方法,但有时候会报出连接已经关闭,无法继续操作的异常。直接上代码了:首先是测试代码:
public class Test {
public st…
因为相信,所以看见。
2020-05-27 10:04:26
7 浏览量
回答数 1
回答
如果需求变化不大!mybatis也是个不错的选择######既然是SSH,那么就交给Spring来管理你的hibernate的sessionFactory, 然后通过sessionFactory来进行相应的数据操作。 Spring和Hibernate的集成,google下,应该有很多标准的配置。######可以看下springside里面的dao,封装的不错######我用ssh做一个增删改查的小案例,用的很模糊,各位朋友可否指导一下呢,小弟谢过了.######
/** 写一段给你,希望对你有帮助 * / import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.; import org.hibernate.; import org.hibernate.type.Type; import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class BaseHibernateDao extends HibernateDaoSupport {
public BaseHibernateDao()
{
}
public void delete(Object entity)
{
getHibernateTemplate().delete(entity);
}
public void delete(Serializable id, Class clazz)
{
delete(getEntity(id, clazz));
}
public void deleteAll(Collection c)
{
for (Iterator iter = c.iterator(); iter.hasNext(); delete(iter.next()));
}
public void evict(Object entity)
{
getHibernateTemplate().evict(entity);
}
public void executeSql(String sql)
{
Connection con;
Session session = getSession();
con = session.connection();
PreparedStatement pst = null;
try {
pst = con.prepareStatement(sql);
pst.execute();
pst.close();
} catch (Exception e) {
throw new BusinessException(“执行SQL语句时出错!”, e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException e) {
throw new BusinessException(“执行SQL语句时出错!”, e);
}
}
}
public void flush()
{
getHibernateTemplate().flush();
}
private Query genQuery(String hql, Object conditionValues[])
{
Query query = genQuery(hql);
setQueryConditionValue(hql, conditionValues, query);
return query;
}
private Query genQuery(String hql)
{
return getSession().createQuery(hql);
}
public List getEntities(String hql, Object conditionValues[])
{
Query query = genQuery(hql, conditionValues);
return query.list();
}
public List getEntities(String hql)
{
Query query = genQuery(hql);
return query.list();
}
public List getEntities(String hql, Object conditionNames[], Object conditionValues[])
{
Query query = getQuery(hql, conditionNames, conditionValues);
return query.list();
}
public Query getQuery(String hql, Object conditionNames[], Object conditionValues[])
{
if (conditionNames.length != conditionValues.length)
throw new BusinessException(“参数和值的数组长度不匹配,长度必需相等!”);
getHibernateTemplate().setCacheQueries(true);
Query query = getSession().createQuery(hql);
if (conditionValues != null)
{
for (int i = 0; i < conditionValues.length; i )
{
Object param = conditionValues[i];
if (param == null)
throw new BusinessException((new StringBuilder(“执行HQL为:”)).append(hql).append(” 查询的时候验证参数出错,第 “).append(i 1).append(” 个参数值为null!”).toString());
if (param instanceof Object[])
query.setParameterList((String)conditionNames[i], (Object[])param);
else
if (param instanceof Collection)
query.setParameterList((String)conditionNames[i], (Collection)param);
else
query.setParameter((String)conditionNames[i], param);
}
}
return query;
}
public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], Object conditionValues[])
{
SQLQuery query = getSession().createSQLQuery(nativeSql);
if (kids.length != clazzs.length)
throw new BusinessException(“参数和值的数组长度不匹配,长度必需相等!”);
if (clazzs != null)
{
for (int i = 0; i < clazzs.length; i )
query.addEntity(kids[i], clazzs[i]);
}
if (conditionValues != null)
{
for (int i = 0; i < conditionValues.length; i )
{
Object param = conditionValues[i];
if (param == null)
throw new BusinessException((new StringBuilder(“执行原生SQL为:”)).append(nativeSql).append(” 验证参数时出错,第 “).append(i 1).append(” 个参数值为null!”).toString());
if (param instanceof Object[])
throw new BusinessException((new StringBuilder(“执行原生SQL为:”)).append(nativeSql).append(” 验证参数时出错,第 “).append(i 1).append(” 个参数值为数组!”).toString());
if (param instanceof Collection)
throw new BusinessException((new StringBuilder(“执行原生SQL为:”)).append(nativeSql).append(” 验证参数时出错,第 “).append(i 1).append(” 个参数值为列表!”).toString());
query.setParameter(i, param);
}
}
return query.list();
}
public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], Object conditionValues[], String scalars[], Type types[])
{
SQLQuery query = getSession().createSQLQuery(nativeSql);
if (clazzs != null)
{
for (int i = 0; i < clazzs.length; i )
query.addEntity(kids[i], clazzs[i]);
}
return null;
}
public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[])
{
SQLQuery query = getSession().createSQLQuery(nativeSql);
if (clazzs != null)
{
for (int i = 0; i < clazzs.length; i )
query.addEntity(kids[i], clazzs[i]);
}
return query.list();
}
public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], String as[], Type atype[])
{
return null;
}
public Object getEntity(Serializable id, Class clazz)
{
Object entity = getHibernateTemplate().get(clazz, id);
return entity != null ? entity : BeanUtil.newInstance(clazz);
}
public Object insert(Object entity)
{
getHibernateTemplate().save(entity);
return entity;
}
public Object loadEntity(Serializable id, Class clazz)
{
Object entity = getHibernateTemplate().load(clazz, id);
return entity != null ? entity : BeanUtil.newInstance(clazz);
}
public Object save(Object entity)
{
if (LogUtil.getIdentify(entity) == null)
getHibernateTemplate().save(entity);
else
getHibernateTemplate().saveOrUpdate(entity);
return entity;
}
private void setQueryConditionValue(String hql, Object conditionValues[], Query query)
{
if (conditionValues != null)
{
for (int i = 0; i < conditionValues.length; i )
{
Object param = conditionValues[i];
if (param == null)
throw new BusinessException((new StringBuilder(“执行HQL为:”)).append(hql).append(” 验证参数时出错,第 “).append(i 1).append(” 个参数值为null!”).toString());
if (param instanceof Object[])
throw new BusinessException((new StringBuilder(“执行HQL为:”)).append(hql).append(” 验证参数时出错,第 “).append(i 1).append(” 个参数值为数组!”).toString());
if (param instanceof Collection)
throw new BusinessException((new StringBuilder(“执行HQL为:”)).append(hql).append(” 验证参数时出错,第 “).append(i 1).append(” 个参数值为列表!”).toString());
query.setParameter(i, param);
}
}
}
public Object uniqueResult(String hql, Object conditionValues[])
{
Query query = genQuery(hql, conditionValues);
return query.uniqueResult();
}
public Object update(Object entity)
{
getHibernateTemplate().update(entity);
return entity;
}
public void updateOrDelete(String hql)
{
Session session = getSession();
Query query = session.createQuery(hql);
query.executeUpdate();
session.flush();
session.clear();
}
public void updateOrDelete(String hql, Object conditionValues[])
{
Session session = getSession();
Query query = session.createQuery(hql);
setQueryConditionValue(hql, conditionValues, query);
query.executeUpdate();
session.flush();
session.clear();
}
public void updateOrDetete(String hql, Map map)
{
Query query = getQuery(hql, map.keySet().toArray(), map.values().toArray());
query.executeUpdate();
getSession().flush();
getSession().clear();
}
public List getAllEntitys(Class clazz, String sort[])
{
StringBuffer hql = new StringBuffer(“select o from “);
hql.append(clazz.getName()).append(” o “);
String as[];
int j = (as = sort).length;
for (int i = 0; i < j; i )
{
String sor = as[i];
if (sor != null && !””.equals(sor))
hql.append(” order by “).append(sor);
}
return getEntities(hql.toString());
}
public PageInfo getEntities_Page(String hql, Object conditionNames[], Object conditionValues[], PageInfo page)
{
Long totalCount = getTotalCount(hql, conditionNames, conditionValues);
Long totalPages = new Long((new Double(Math.ceil(totalCount.longValue() / page.getPageSize().longValue()))).intValue());
totalPages = Long.valueOf(totalCount.longValue() % page.getPageSize().longValue() != 0L ? totalPages.longValue() (new Long(1L)).longValue() : totalPages.longValue());
PageInfo pageInfo = new PageInfo();
pageInfo.setPageSize(page.getPageSize());
pageInfo.setPage(page.getPage());
pageInfo.setTotalSize(totalCount);
pageInfo.setPageCount(totalPages);
Query query = getQuery(hql, conditionNames, conditionValues);
query.setFirstResult((page.getPage().intValue() – 1) * page.getPageSize().intValue());
query.setMaxResults(page.getPageSize().intValue());
List list = query.list();
pageInfo.setData(list);
return pageInfo;
}
private Long getTotalCount(String hql, Object conditionNames[], Object conditionValues[])
{
Long totalCount = new Long(0L);
String lowerhql = hql.toLowerCase();
String totalHql = new String(“”);
int fIndex = lowerhql.indexOf(” from “);
if (fIndex < 0)
fIndex = 0;
else
fIndex ;
int orderLastIndex = lowerhql.lastIndexOf(” order by “);
if (orderLastIndex > 0)
totalHql = (new StringBuilder(“select count(*) “)).append(hql.substring(fIndex, orderLastIndex)).append(” “).toString();
else
totalHql = (new StringBuilder(“select count(*) “)).append(hql.substring(fIndex)).append(” “).toString();
List list = getEntities(totalHql, conditionNames, conditionValues);
Number num = (Number)list.get(0);
totalCount = new Long(num.longValue());
return totalCount;
}
protected User getOper()
{
User oper = (User)SingleThreadImpl.getInstance().get(“user_context”);
return oper;
}
}######O(∩_∩)O谢谢,非常有用.######批量删除建议修改下,效率太慢.
kun坤
2020-06-09 11:45:32
0 浏览量
回答数 0
问题
JDBC sqlite一直报错??报错
Class.forName(“org.sqlite.JDBC”); Connection conn = DriverManager.getConnection(“jdbc:sqlite:t…
爱吃鱼的程序员
2020-06-14 20:53:50
0 浏览量
回答数 1
问题
Spring3 hibernate3 在dao层使用Query的executeU?400报错
Spring3 hibernate3 在dao层使用Query的executeUpdate不回滚? 400 报错
Dao层
@Override public int updateRetrailState(Inte…
爱吃鱼的程序员
2020-05-31 00:40:57
0 浏览量
回答数 1
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/179772.html原文链接:https://javaforall.cn