Search Results

Search found 34 results on 2 pages for 'jdbctemplate'.

Page 1/2 | 1 2  | Next Page >

  • Spring JdbcTemplate - Insert blob and return generated key

    - by itsadok
    From the Spring JDBC documentation, I know how to insert a blob using JdbcTemplate final File blobIn = new File("spring2004.jpg"); final InputStream blobIs = new FileInputStream(blobIn); jdbcTemplate.execute( "INSERT INTO lob_table (id, a_blob) VALUES (?, ?)", new AbstractLobCreatingPreparedStatementCallback(lobhandler) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setLong(1, 1L); lobCreator.setBlobAsBinaryStream(ps, 2, blobIs, (int)blobIn.length()); } } ); blobIs.close(); And also how to retrieve the generated key of a newly inserted row: KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] {"id"}); ps.setString(1, name); return ps; } }, keyHolder); // keyHolder.getKey() now contains the generated key Is there a way I could combine the two?

    Read the article

  • How to truncate a table with Spring JdbcTemplate?

    - by Marcus
    I'm trying to truncate a table with Spring: jdbcTemplate.execute("TRUNCATE TABLE " + table); Get the error: Caused by: org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [TRUNCATE TABLE RESULT_ACCOUNT]; nested exception is java.sql.SQLException: Unexpected token: TRUNCATE in statement [TRUNCATE] Any ideas?

    Read the article

  • SimpleJdbcCall ignoring JdbcTemplate fetch size

    - by user289429
    We are calling the pl/sql stored procedure through Spring SimpleJdbcCall, the fetchsize set on the JdbcTemplate is being ignored by SimpleJdbcCall. The rowmapper resultset fetch size is set to 10 even though we have set the jdbctemplate fetchsize to 200. Any idea why this happens and how to fix it? Have printed the fetchsize of resultset in the rowmapper in the below code snippet - Once it is 200 and other time it is 10 even though I use the same JdbcTemplate on both occassion. This direct execution through jdbctemplate returns fetchsize of 200 in the row mapper jdbcTemplate = new JdbcTemplate(ds); jdbcTemplate.setResultsMapCaseInsensitive(true); jdbcTemplate.setFetchSize(200); List temp = jdbcTemplate.query("select 1 from dual", new ParameterizedRowMapper() { public Object mapRow(ResultSet resultSet, int i) throws SQLException { System.out.println("Direct template : " + resultSet.getFetchSize()); return new String(resultSet.getString(1)); } }); This execution through SimpleJdbcCall is always returning fetchsize of 10 in the rowmapper jdbcCall = new SimpleJdbcCall(jdbcTemplate).withSchemaName(schemaName) .withCatalogName(catalogName).withProcedureName(functionName); jdbcCall.returningResultSet((String) outItValues.next(), new ParameterizedRowMapper<Map<String, Object>>() { public Map<String, Object> mapRow(ResultSet rs, int row) throws SQLException { System.out.println("Through simplejdbccall " + rs.getFetchSize()); return extractRS(rs, row); } }); outputList = (List<Map<String, Object>>) jdbcCall.executeObject(List.class, inParam);

    Read the article

  • Using prepared statements with JDBCTemplate

    - by Bernhard V
    Hi. I'm using the Jdbc template and want to read from the database using prepared statements. I iterate over many lines in a csv file and on every line I execute some sql select queries with it's values. Now I want to speed up my reading from the database but I just can't get the Jdbc template to work with prepared statements. Actually I even don't know how to do it. There is the PreparedStatementCreator and the PreparedStatementCreator. As in this example both of them are created with anonymous inner classes. But inside the PreparedStatementCreator class I don't have access to the values I want to set in the prepared statement. Since I'm iterating through a csv file I can't hard code them as a String because I don't know them. I also can't pass them to the PreparedStatementCreator because there are no arguments for the constructor. I was used to the creation of prepared statements being fairly simple. Something like PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? "); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(): as in the Java tutorial. Your help would be very appreciated.

    Read the article

  • How to make a thread try to reconnect to the Database x times using JDBCTemplate

    - by gillJ
    Hi, I have a single thread trying to connect to a database using JDBCTemplate as follows: JDBCTemplate jdbcTemplate = new JdbcTemplate(dataSource); try{ jdbcTemplate.execute(new CallableStatementCreator() { @Override public CallableStatement createCallableStatement(Connection con) throws SQLException { return con.prepareCall(query); } }, new CallableStatementCallback() { @Override public Object doInCallableStatement(CallableStatement cs) throws SQLException { cs.setString(1, subscriberID); cs.execute(); return null; } }); } catch (DataAccessException dae) { throw new CougarFrameworkException( "Problem removing subscriber from events queue: " + subscriberID, dae); } I want to make sure that if the above code throws DataAccessException or SQLException, the thread waits a few seconds and tries to re-connect, say 5 more times and then gives up. How can I achieve this? Also, if during execution the database goes down and comes up again, how can i ensure that my program recovers from this and continues running instead of throwing an exception and exiting?

    Read the article

  • using JdcbTemplate standalone

    - by Flyhard
    Hi We are looking into using the JdbcTemplate for accessing the DB - but we have many different DB-connections, that each class could use, so injecting the jdbcTemplate is not an option atm. So if we do a jdbcTemplate = new JdbcTemplate(dataSource); what will the transaction policy be? Auto-commit is off in the DB.

    Read the article

  • using Spring JdbcTemplate for multiple database operations

    - by Joel Carranza
    I like the apparent simplicity of JdbcTemplate but am a little confused as to how it works. It appears that each operation (query() or update()) fetches a connection from a datasource and closes it. Beautiful, but how do you perform multiple SQL queries within the same connection? I might want to perform multiple operations in sequence (for example SELECT followed by an INSERT followed by a commit) or I might want to perform nested queries (SELECT and then perform a second SELECT based on result of each row). How do I do that with JdbcTemplate. Am I using the right class?

    Read the article

  • Dynamically select field names in a query with Spring JDBCTemplate

    - by Francesco
    Hi, I have a problem with parameters replacing by Spring JdbcTemplate. I have this query : <bean id="fixQuery" class="java.lang.String"> <constructor-arg type="java.lang.String" value="select fa.id, fi.? from fix_ambulation fa left join fix_i18n fi on fa.translation_id = fi.id order by name" /> And this method : public List<FixAmbulation> readFixAmbulation(String locale) throws Exception { List<FixAmbulation> ambulations = this.getJdbcTemplate().query( fixQuery, new Object[] {locale.toLowerCase()}, ParameterizedBeanPropertyRowMapper .newInstance(FixAmbulation.class)); return ambulations; } And I'd like to have the ? filled with the string representing the locale the user is using. So if the user is brasilian I'd send him the column pt_br from the table fix_i18n, otherwise if he's american I'd send him the column en_us. What I get from this method is a PostgreSQL exception org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1" If I replace fi.? with just ? (the column name of the locale is unique, so if I run this query in the database it works just fine) what I get is that every object returned from method has the string locale into the field name. I.e. in name field I have "en_us". The only way to have it working I found was to change the method into : public List<FixAmbulation> readFixAmbulation(String locale) throws Exception { String query = "select fa.id, fi." + locale.toLowerCase() + " as name " + fixQuery; this.log.info("QUERY : " + query); List<FixAmbulation> ambulations = this.getJdbcTemplate().query( query, ParameterizedBeanPropertyRowMapper .newInstance(FixAmbulation.class)); return ambulations; } and setting fixQuery to : <bean id="fixQuery" class="java.lang.String"> <constructor-arg type="java.lang.String" value=" from telemedicina.fix_ambulation fa left join telemedicina.fix_i18n fi on fa.translation_id = fi.id order by name" /> </bean> My DAO extends Spring JdbcDaoSupport and works just fine for all other queries. What am I doing wrong?

    Read the article

  • MySQL Connection error in spring MVC

    - by nidhi
    i am working on spring MVC facing the following exception while connecting to my sql. Blocorg.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:572) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:636) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:665) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:673) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:728) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:744) at org.springframework.jdbc.core.JdbcTemplate.queryForInt(JdbcTemplate.java:775) at com.trackmeetings.dao.InboxDAOImpl.getNotificationsCount(InboxDAOImpl.java:51) at com.trackmeetings.service.InboxService.getNotificationsCount(InboxService.java:56) at com.trackmeetings.controller.HomePageController.getLogInUserDetails(HomePageController.java:80) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.trackmeetings.util.NoCacheFilter.doFilter(NoCacheFilter.java:56) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:680) Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.) at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1225) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) ... 38 more Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failurekquote how can i resolve this. please help,

    Read the article

  • Connection error in java website. Tnsping shows that the service is running

    - by user1439090
    I have a java website application running in windows 7 which uses oracle database for its functionalities. The database has default SID name orcl. When I use tnsping, I can see that the orcl service is active. Also most of the application is working fine except for one part. I was wondering if someone could help me with the following error:- 1. cause: message:null,java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.olat.course.statistic.StatisticAutoCreator.createController(StatisticAutoCreator.java:73) at org.olat.course.statistic.StatisticActionExtension.createController(StatisticActionExtension.java:40) at org.olat.course.statistic.StatisticMainController.createController(StatisticMainController.java:80) at org.olat.core.gui.control.generic.layout.GenericMainController.getContentCtr(GenericMainController.java:258) at org.olat.core.gui.control.generic.layout.GenericMainController.event(GenericMainController.java:221) at org.olat.core.gui.control.DefaultController.dispatchEvent(DefaultController.java:196) 2. cause: message:Could not get JDBC Connection; nested exception is java.sql.SQLException: The Network Adapter could not establish the connection,org.springframework.jdbc.CannotGetJdbcConnectionException at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:381) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:455) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:463) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:471) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:476) at org.springframework.jdbc.core.JdbcTemplate.queryForLong(JdbcTemplate.java:480) at org.olat.course.statistic.SimpleStatisticInfoHelper.doGetFirstLoggingTableCreationDate(SimpleStatisticInfoHelper.java:63) at org.olat.course.statistic.SimpleStatisticInfoHelper.getFirstLoggingTableCreationDate(SimpleStatisticInfoHelper.java:81) at org.olat.course.statistic.StatisticDisplayController.getStatsSinceStr(StatisticDisplayController.java:517) 3. cause: message:The Network Adapter could not establish the connection,java.sql.SQLException at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70) at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:480) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:413) at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:508) at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:203) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510) at java.sql.DriverManager.getConnection(DriverManager.java:582) 4. cause: message:The Network Adapter could not establish the connection,oracle.net.ns.NetException at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:328) at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:421) at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:634) at oracle.net.ns.NSProtocol.connect(NSProtocol.java:208) at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:966) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:292) at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:508) at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:203) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510) 5. cause: message:Connection timed out: connect,java.net.ConnectException at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:525) at java.net.Socket.connect(Socket.java:475) at java.net.Socket.(Socket.java:372) at java.net.Socket.(Socket.java:186) at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:127)

    Read the article

  • Firebird query is crashing with org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544364. reque

    - by user321395
    I am using JdbcTemplate.queryForInt to insert a Row into the DB, and then get the ID back. The Query is "INSERT INTO metadocs(NAME) values (?) RETURNING METADOCID". If I run the statement in Flamerobin, it works fine. However, if I run it from Java, I get the following error: org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [INSERT INTO metadocs(NAME) values (?) RETURNING METADOCID]; SQL state [HY000]; error code [335544364]; GDS Exception. 335544364. request synchronization error; nested exception is org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544364. request synchronization error Caused by: org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544364. request synchronization error Does anyone have an idea what this could be caused by?

    Read the article

  • Using Spring's KeyHolder with programmatically-generated primary keys

    - by smayers81
    Hello, I am using Spring's NamedParameterJdbcTemplate to perform an insert into a table. The table uses a NEXTVAL on a sequence to obtain the primary key. I then want this generated ID to be passed back to me. I am using Spring's KeyHolder implementation like this: KeyHolder key = new GeneratedKeyHolder(); jdbcTemplate.update(Constants.INSERT_ORDER_STATEMENT, params, key); However, when I run this statement, I am getting: org.springframework.dao.DataRetrievalFailureException: The generated key is not of a supported numeric type. Unable to cast [oracle.sql.ROWID] to [java.lang.Number] at org.springframework.jdbc.support.GeneratedKeyHolder.getKey(GeneratedKeyHolder.java:73) Any ideas what I am missing?

    Read the article

  • How can you connect to a password protected MS Access Database from a Spring JdbcTemplate?

    - by Tim Visher
    I need to connect to a password protected MS Access 2003 DB using the JDBC-ODBC bridge. I can't find out how to specify the password in the connect string, or even if that is the correct method of connecting. It would probably be relevant to mention that this is a Spring App which is accessing the database through a JdbcTemplate configured as a datasource bean in our application context file. Some relevant snippets: from application-context.xml <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="legacyDataSource" /> </bean> <bean id="jobsheetLocation" class="java.lang.String"> <constructor-arg value="${jobsheet.location}"/> </bean> <bean id="legacyDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.legacy.driverClassName}" /> <property name="url" value="${jdbc.legacy.url}"/> <property name="password" value="-------------" /> </bean> from our build properties jdbc.legacy.driverClassName=sun.jdbc.odbc.JdbcOdbcDriver jdbc.legacy.url=jdbc:odbc:Driver\={Microsoft Access Driver (*.mdb)};Dbq\=@LegacyDbPath@;DriverID\=22;READONLY\=true Any thoughts?

    Read the article

  • What transaction manager should I use for JBDC template When using JPA ?

    - by Sajid
    I am using standard JPA transaction manager for my JPA transactions. However, now I want to add some JDBC entities which will share the same 'datasource'. How can I make the JDBC operations transactional with spring transaction? Do I need to swith to JTA transaction managers? Is it possible to use both JPA & JDBC transactional service with same datasource? Even better, is it possible to mix these two transactions?

    Read the article

  • spring JDBC

    - by Adhir
    I am getting the following exception whe using derby to do a UPDATE in oracle Database org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.derby.client.am.DisconnectException: A communication error has been detected. Communication protocol being used: Reply.fill(). Communication API being used: InputStream.read(). Location where the error was detected: insufficient data. Communication function detecting the error: *. Protocol specific error codes(s) TCP/IP SOCKETS at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:522) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:737) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:795) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:803) at com.poc.data.dao.UserDerbyDao.create(UserDerbyDao.java:19) at com.poc.register.RegisterUtil.registerUser(RegisterUtil.java:34) at com.poc.service.MyService.doRegister(MyService.java:108) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:175) at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67) at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:166) at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:114) at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:74) at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:114) at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:66) at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:658) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:616) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:607) at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590) at javax.servlet.http.HttpServlet.service(HttpServlet.java:806) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: org.apache.derby.client.am.DisconnectException: A communication error has been detected. Communication protocol being used: Reply.fill(). Communication API being used: InputStream.read(). Location where the error was detected: insufficient data. Communication function detecting the error: *. Protocol specific error codes(s) TCP/IP SOCKETS at org.apache.derby.client.net.NetAgent.throwCommunicationsFailure(Unknown Source) at org.apache.derby.client.net.Reply.fill(Unknown Source) at org.apache.derby.client.net.Reply.ensureALayerDataInBuffer(Unknown Source) at org.apache.derby.client.net.Reply.readDssHeader(Unknown Source) at org.apache.derby.client.net.Reply.startSameIdChainParse(Unknown Source) at org.apache.derby.client.net.NetConnectionReply.readExchangeServerAttributes(Unknown Source) at org.apache.derby.client.net.NetConnection.readServerAttributesAndKeyExchange(Unknown Source) at org.apache.derby.client.net.NetConnection.flowServerAttributesAndKeyExchange(Unknown Source) at org.apache.derby.client.net.NetConnection.flowUSRIDPWDconnect(Unknown Source) at org.apache.derby.client.net.NetConnection.flowConnect(Unknown Source) at org.apache.derby.client.net.NetConnection.(Unknown Source) at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:291) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:277) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:259) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:240) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:113) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79) ... 37 more Any help Thanks in advance Adhir

    Read the article

  • Spring security - Reach users ID without passing it through every controller

    - by nilsi
    I have a design issue that I don't know how to solve. I'm using Spring 3.2.4 and Spring security 3.1.4. I have a Account table in my database that looks like this: create table Account (id identity, username varchar unique, password varchar not null, firstName varchar not null, lastName varchar not null, university varchar not null, primary key (id)); Until recently my username was just only a username but I changed it to be the email address instead since many users want to login with that instead. I have a header that I include on all my pages which got a link to the users profile like this: <a href="/project/users/<%= request.getUserPrincipal().getName()%>" class="navbar-link"><strong><%= request.getUserPrincipal().getName()%></strong></a> The problem is that <%= request.getUserPrincipal().getName()%> returns the email now, I don't want to link the user's with thier emails. Instead I want to use the id every user have to link to the profile. How do I reach the users id's from every page? I have been thinking of two solutions but I'm not sure: Change the principal to contain the id as well, don't know how to do this and having problem finding good information on the topic. Add a model attribute to all my controllers that contain the whole user but this would be really ugly, like this. Account account = entityManager.find(Account.class, email); model.addAttribute("account", account); There are more way's as well and I have no clue which one is to prefer. I hope it's clear enough and thank you for any help on this. ====== Edit according to answer ======= I edited Account to implement UserDetails, it now looks like this (will fix the auto generated stuff later): @Entity @Table(name="Account") public class Account implements UserDetails { @Id private int id; private String username; private String password; private String firstName; private String lastName; @ManyToOne private University university; public Account() { } public Account(String username, String password, String firstName, String lastName, University university) { this.username = username; this.password = password; this.firstName = firstName; this.lastName = lastName; this.university = university; } public String getUsername() { return username; } public String getPassword() { return password; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public University getUniversity() { return university; } public void setUniversity(University university) { this.university = university; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { // TODO Auto-generated method stub return null; } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return false; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return false; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return false; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return true; } } I also added <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> To my jsp files and trying to reach the id by <sec:authentication property="principal.id" /> This gives me the following org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.id' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal.id' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? ====== Edit 2 according to answer ======= I based my application on spring social samples and I never had to change anything until now. This are the files I think are relevant, please tell me if theres something you need to see besides this. AccountRepository.java public interface AccountRepository { void createAccount(Account account) throws UsernameAlreadyInUseException; Account findAccountByUsername(String username); } JdbcAccountRepository.java @Repository public class JdbcAccountRepository implements AccountRepository { private final JdbcTemplate jdbcTemplate; private final PasswordEncoder passwordEncoder; @Inject public JdbcAccountRepository(JdbcTemplate jdbcTemplate, PasswordEncoder passwordEncoder) { this.jdbcTemplate = jdbcTemplate; this.passwordEncoder = passwordEncoder; } @Transactional public void createAccount(Account user) throws UsernameAlreadyInUseException { try { jdbcTemplate.update( "insert into Account (firstName, lastName, username, university, password) values (?, ?, ?, ?, ?)", user.getFirstName(), user.getLastName(), user.getUsername(), user.getUniversity(), passwordEncoder.encode(user.getPassword())); } catch (DuplicateKeyException e) { throw new UsernameAlreadyInUseException(user.getUsername()); } } public Account findAccountByUsername(String username) { return jdbcTemplate.queryForObject("select username, firstName, lastName, university from Account where username = ?", new RowMapper<Account>() { public Account mapRow(ResultSet rs, int rowNum) throws SQLException { return new Account(rs.getString("username"), null, rs.getString("firstName"), rs.getString("lastName"), new University("test")); } }, username); } } security.xml <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <http pattern="/resources/**" security="none" /> <http pattern="/project/" security="none" /> <http use-expressions="true"> <!-- Authentication policy --> <form-login login-page="/signin" login-processing-url="/signin/authenticate" authentication-failure-url="/signin?error=bad_credentials" /> <logout logout-url="/signout" delete-cookies="JSESSIONID" /> <intercept-url pattern="/addcourse" access="isAuthenticated()" /> <intercept-url pattern="/courses/**/**/edit" access="isAuthenticated()" /> <intercept-url pattern="/users/**/edit" access="isAuthenticated()" /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider> <password-encoder ref="passwordEncoder" /> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username, password, true from Account where username = ?" authorities-by-username-query="select username, 'ROLE_USER' from Account where username = ?"/> </authentication-provider> <authentication-provider> <user-service> <user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans> And this is my try of implementing a UserDetailsService public class RepositoryUserDetailsService implements UserDetailsService { private final AccountRepository accountRepository; @Autowired public RepositoryUserDetailsService(AccountRepository repository) { this.accountRepository = repository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Account user = accountRepository.findAccountByUsername(username); if (user == null) { throw new UsernameNotFoundException("No user found with username: " + username); } return user; } } Still gives me the same error, do I need to add the UserDetailsService somewhere? This is starting to be something else compared to my initial question, I should maybe start another question. Sorry for my lack of experience in this. I have to read up.

    Read the article

  • Getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver Exception

    - by Yashwant Chavan
    Hi , I am getting Following Exception while configuring the Connection Pool in Tomcat This is Context.xml <Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true"> <!-- maxActive: Maximum number of dB connections in pool. Make sure you configure your mysqld max_connections large enough to handle all of your db connections. Set to -1 for no limit. --> <!-- maxIdle: Maximum number of idle dB connections to retain in pool. Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis configuration parameter. --> <!-- maxWait: Maximum time to wait for a dB connection to become available in ms, in this example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely. --> <!-- username and password: MySQL dB username and password for dB connections --> <!-- driverClassName: Class name for the old mm.mysql JDBC driver is org.gjt.mm.mysql.Driver - we recommend using Connector/J though. Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver. --> <!-- url: The JDBC connection url for connecting to your MySQL dB. --> <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="password" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql:///BUSINESS"/> </Context> This is Bean Entry <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="jdbc/TestDB"></property> <property name="resourceRef" value="true"></property> </bean> org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Co nnection; nested exception is org.apache.tomcat.dbcp.dbcp.SQLNestedException: Ca nnot load JDBC driver class 'com.mysql.jdbc.Driver' at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(Dat aSourceUtils.java:82) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java: 382) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:45 8) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:46 6) at com.businesscaliber.dao.Dao.getQueryForListMap(Dao.java:66) at com.businesscaliber.dao.MiscellaneousDao.getDefaultSucessStory(Miscel laneousDao.java:109) at com.businesscaliber.listeners.BusinessContextLoader.contextInitialize d(BusinessContextLoader.java:40) at org.apache.catalina.core.StandardContext.listenerStart(StandardContex t.java:3795) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4 252) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase .java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:74 0) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:831) at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:720 ) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490 ) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java :311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(Lifecycl eSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443 ) at org.apache.catalina.core.StandardService.start(StandardService.java:4 48) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700 ) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) Caused by: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driv er class 'com.mysql.jdbc.Driver' at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDat aSource.java:1136) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSo urce.java:880) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(D ataSourceUtils.java:113) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(Dat aSourceUtils.java:79) ... 30 more Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:164) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDat aSource.java:1130)

    Read the article

  • How to manage a large dataset using Spring MySQL and RowCallbackHandler

    - by rmarimon
    I'm trying to go over each row of a table in MySQL using Spring and a JdbcTemplate. If I'm not mistaken this should be as simple as: JdbcTemplate template = new JdbcTemplate(datasource); template.setFetchSize(1); // template.setFetchSize(Integer.MIN_VALUE) does not work either template.query("SELECT * FROM cdr", new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { System.out.println(rs.getString("src")); } }); I get an OutOfMemoryError because it is trying to read the whole thing. Any ideas?

    Read the article

  • Foreign/accented characters in sql query

    - by FromCanada
    I'm using Java and Spring's JdbcTemplate class to build an SQL query in Java that queries a Postgres database. However, I'm having trouble executing queries that contain foreign/accented characters. For example the (trimmed) code: JdbcTemplate select = new JdbcTemplate( postgresDatabase ); String query = "SELECT id FROM province WHERE name = 'Ontario';"; Integer id = select.queryForObject( query, Integer.class ); will retrieve the province id, but if instead I did name = 'Québec' then the query fails to return any results (this value is in the database so the problem isn't that it's missing). I believe the source of the problem is that the database I am required to use has the default client encoding set to SQL_ASCII, which according to this prevents automatic character set conversions. (The Java environments encoding is set to 'UTF-8' while I'm told the database uses 'LATIN1' / 'ISO-8859-1') I was able to manually indicate the encoding when the resultSets contained values with foreign characters as a solution to a previous problem with a similar nature. Ex: String provinceName = new String ( resultSet.getBytes( "name" ), "ISO-8859-1" ); But now that the foreign characters are part of the query itself this approach hasn't been successful. (I suppose since the query has to be saved in a String before being executed anyway, breaking it down into bytes and then changing the encoding only muddles the characters further.) Is there a way around this without having to change the properties of the database or reconstruct it? PostScript: I found this function on StackOverflow when making up a title, it didn't seem to work (I might not have used it correctly, but even if it did work it doesn't seem like it could be the best solution.):

    Read the article

  • Assert a good practice or not ?

    - by rkenshin
    Is it a good practice to use Assert for function parameters to enforce their validity. I was going through the source code of Spring Framework and I noticed that they use Assert.notNull a lot. Here's an example public static ParsedSql parseSqlStatement(String sql) { Assert.notNull(sql, "SQL must not be null");} Here's Another one public NamedParameterJdbcTemplate(DataSource dataSource) { Assert.notNull(dataSource, "The [dataSource] argument cannot be null."); this .classicJdbcTemplate = new JdbcTemplate(dataSource); } public NamedParameterJdbcTemplate(JdbcOperations classicJdbcTemplate) { Assert.notNull(classicJdbcTemplate, "JdbcTemplate must not be null"); this .classicJdbcTemplate = classicJdbcTemplate; } Thank you

    Read the article

  • java.lang.OutOfMemory error when fetching records from Database

    - by Nisarg Mehta
    Hi All, When I try to fetch around 20,000 records and return to ArrayList then it throws java heap space error. JdbcTemplate select = new JdbcTemplate(dataSource); String SQL_SELECT_XML_IRP_ADDRESS = " SELECT * FROM "+ SCHEMA +".XML_ADDRESS "+ " WHERE FILE_NAME = ? "; Object[] parameters=new Object[] {xmlFileName}; return (ArrayList<XmlAddressDto> ) select.query(SQL_SELECT_XML_ADDRESS, parameters,new XmAddressMapExt()); Is there any solution for this ? How should i process this effectively ?

    Read the article

  • Database connection management in Spring

    - by ria
    Do we have to explicitly manage database resources when using Spring Framework.. liking closing all open connections etc? I have read that Spring relieves developer from such boiler plate coding... This is to answer an error that I am getting in a Spring web app: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: ORA-00020: maximum number of processes (150) exceeded The jdbcTemplate is configured in the xml file and the DAO implementation has reference to this jdbcTemplate bean which is used to query the database.

    Read the article

  • Spring Jdbc Template + MySQL = TransientDataAccessResourceException : Invalid Argument Value : Java.

    - by Vanchinathan
    I was using spring jdbc template to insert some data into the database and I was getting this error. Here is my code : JdbcTemplate insert = new JdbcTemplate(dataSource); for(ResultType result : response.getResultSet().getResult()) { Object[] args = new Object[] {result.getAddress(), result.getCity(), result.getState(), result.getPhone(), result.getLatitude(), result.getLongitude(),result.getRating().getAverageRating(), result.getRating().getAverageRating(), result.getRating().getTotalRatings(), result.getRating().getTotalReviews(), result.getRating().getLastReviewDate(), result.getRating().getLastReviewIntro(), result.getDistance(), result.getUrl(), result.getClickUrl(), result.getBusinessUrl(), result.getBusinessClickUrl()}; insert.update("INSERT INTO data.carwashes ( address, city, state, phone, lat, lng, rating, average_rating, total_ratings, total reviews, last_review_date, last_review_intro, distance, url, click_url, business_url, business_click_url, category_id, zipcode_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,96925724,78701)", args); } Quite lengthy code.. but, basically it gets the value from a object and sticks it to a array and passed that array to insert method of jdbc template. Any help will be appreciated.

    Read the article

1 2  | Next Page >