hibernate,postgresql,transactions,junit4,spring-4 , hibernate rollback not working in service layer


hibernate rollback not working in service layer

Question:

Tag: hibernate,postgresql,transactions,junit4,spring-4

i have issue in rollback insert/update data in postgresql database, in service layer, where as in DAO layer it is working fine.

My DAO junit test Code

@ContextConfiguration("classpath:datasource-context-test.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class SellerDAOTest {
@Test
    @Rollback(true)
    public void testAddSeller() {
        try {
            SellerDO sellerDO = getSellerDO();
            sellerDAOImpl.addSeller(sellerDO);
        } catch (DataException cdExp) {
            Assert.fail();
        }

    }
}

and my dao impl looks like

@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addSeller(SellerDO sellerDO) throws DataException {
    try {
        Session session = this.getSessionFactory().getCurrentSession();
        session.save(sellerDO);
    } catch (HibernateException hExp) {
        throw new DataException("DB Error while adding new seller details", hExp);
    }

}

and above test rollbacks the data inserted after executing the test. but i problem is in my service layer. rollback is not happening in here

@ContextConfiguration({ "classpath:datasource-context-test.xml", "classpath:service-context-test.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
@Component
public class SellerTest {
    @Junit
    @Rollback(true)
    public void testAddSeller() {

        SellerBO sellerBO = getSellerBO();
        try {
            manageSellerServiceImpl.addSeller(sellerBO);
        } catch (ServiceException csExp) {
            Assert.fail();
        }

    }
}

my service code

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addSeller(SellerBO sellerBO) throws ServiceException {
      sellerDAOImpl.addSeller(sellerDO);
}

i dont know why it is not working in service layer. i have tried couple of solution stackoverflow, but none worked. help needed


Answer:

Using REQUIRES_NEW will run your code in a new transaction separately from the one that JUnit creates. So you are creating a nested transaction by invoking your service layer code.

Change Propagation.REQUIRES_NEW to Propagation.REQUIRED in your service layer. Also since Propagation.REQUIRED is the default propagation level, you can remove this annotation.


Related:


How can implement long running process in spring hibernate?


java,spring,hibernate
as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

How to check what constraint has been violated?


java,sql,postgresql,exception
I'm used to check if the user try to store a valid data with cathcing the ConsratinViolationException, like that: try { //persisitng to a db } catch (ConstraintViolationException e){ //Print message } I'm using PostgreSQL and now I'm under the isssue that the persisitng can violate more than one different...

postgres: using previous row value when current row value is null


postgresql
In my app I need to produce a data output (to be then converted to JSON) for the data in a postgres database (which is actually temperature data gathered by sensors). The data is stored in device_history_log as follows (for data between 11am and noon): row_id;deviceid;sensor_value_raw;last_update 104401;20865735;21.56;"2015-06-10 11:00:14" 104432;493417852;23.9;"2015-06-10 11:00:58"...

postgresql complex group by in query


sql,postgresql
I have a query that gives: itemid deadlineneeded delievrydate quantity 200 15/07/15 14/07/15 5 200 15/07/15 14/07/15 10 200 15/07/15 13/07/15 25 201 15/07/15 14/07/15 30 200 14/07/15 10/07/15 3 201 15/07/15 15/07/15 100 It gives the information from multiple tables. Basically it means When items arrive to warehouse (delievrydate)...

unexpected token : ( subquery hql


sql,hibernate,hql
Here's my HQL query FROM com.mysite.ActeurInterne act WHERE act.acteurId IN (SELECT DISTINCT COALESCE(acteurInterne.acteurInternePrincipalId, acteurInterne.acteurId) FROM (SELECT DISTINCT acteurInterne FROM com.mysite.ActeurInterne AS acteurInterne JOIN acteurInterne.roleSet.roles AS role WHERE acteurInterne.acteurId = acteurInterne.acteurId AND acteurInterne.nom LIKE :likenom AND (role.dateFermeture IS NULL OR role.dateFermeture >= TRUNC(SYSDATE)) AND (role.dateOuverture IS NULL OR role.dateOuverture <= TRUNC(SYSDATE))...

Connecting C++ and Postgresql


c++,postgresql,linker-error,libpqxx
I'm trying to connect C++ to Postgres. I recently installed libpqxx with Homebrew as follows: brew install libpqxx Then I made it with: make DatabaseTest on the file DatabaseTest.cpp. I ran the following simple program and got a strange error that I'm not sure what to do with... #include <iostream>...

Prepared statements: Using unnamed and unnumbered question mark style positional placeholders


postgresql
In SQL systems other than Postgres, such as MySQL for instance, prepared statements can use question marks ? as a placeholder for data in prepared statements. INSERT INTO foo (id, name) VALUES (?, ?), (?, ?); However, in Postgres the only available placeholders seem to be the numbered placeholders, so...

How to use Rails #update_attribute with array field?


ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord
Each question has an array of tags. schema.rb: create_table "questions", force: true do |t| t.text "tags", default: [], array: true How to atomically append to tags? How to prevent dups within the array? I tried question.update_attribute tags: tags << :ruby, but this doesn't work. Rails 4.17 and Postgres. EDIT: This...

How to know an object has changed compared to database


java,hibernate,jpa,playframework,playframework-1.x
I need to know if some fields of a model object has been changed before save because I need to compare the new values with the old ones. I can't touch the model classes are they are generated. My problem is that whenever I change an object in a controller...

need help specifying potentially reserved words as strings in postgres query


postgresql
I've been using mysql for close to 10 years, but have recently jumped into a project that's exposed me to postgres for the first time. Most of the differences aren't a bit deal, but I have been running into some small issues along the way that are throwing me off....

Avoid calling COUNT twice in CASE expression (PostgreSQL)


sql,postgresql
Inside a larger query, I have to COUNT a variable, then if it is larger than 1, have the count as a string otherwise an empty string: CASE COUNT(measurement.id) > 1 THEN to_char(COUNT(measurement.id),' 999') ELSE '' I'm afraid this is slow because I use COUNT() twice. Is there a better...

PostgreSQL conditional statement


sql,postgresql,if-statement
I need to implement a conditional SELECT statement based on the result of another statement. I don't want to create a function for this purpose, but simply using conditional SELECT. My unsuccessful approach looks as below: DO $do$ BEGIN IF SELECT count(*) FROM table1 < 1 THEN SELECT * FROM...

How to delete replication slot in postgres 9.4


postgresql,replication,postgresql-9.4
I have replication slot which I want to delete but when I do delete I got an error that I can't delete from view. Any ideas? postgres=# SELECT * FROM pg_replication_slots ; slot_name | plugin | slot_type | datoid | database | active | xmin | catalog_xmin | restart_lsn --------------+--------------+-----------+--------+----------+--------+------+--------------+-------------...

In PostgreSQL is it possible to join between table and function?


sql,postgresql
I have a table named Cars and a function named PartsPerCar there is no direct link between carid and partid. the link is though 3 tables in the middle. I do have a function called PartsPerCar which gets carid (it goves via the tables in the middle) and give back...

Sqoop Export with Missing Data


sql,postgresql,shell,hadoop,sqoop
I am trying to use Sqoop to export data from HDFS into Postgresql. However, I receive an error partially through the export that it can't parse the input. I manually went into the file I was exporting and saw that this row had two columns missing. I have tried a...

Hibernate delete child when parent is getting updated in same transaction


hibernate,spring-data
I have defined two entities Customer and SalesOrder in my domain model with oneToMany relationship from customer to salesOrder. Below code deletes the sales order: SalesOrder salesOrder = salesOrderRepository.findByOrderNumber(orderNumber); if(null != salesOrder){ Customer customer = salesOrder.getCustomer(); customer.setCurrentCredit(customer.getCurrentCredit() - salesOrder.getTotalPrice()); Iterator<SalesOrder> iter = customer.getSalesOrders().iterator(); while(iter.hasNext()){ SalesOrder order = iter.next();...

Can't obtain connection with the DB due to very long schema validation and connection reset afterwards


java,oracle,hibernate
I have an app where I use Hibernate/Oracle 11g XE/Jboss6.2 and I am having trouble starting up the application on my homolog server at DigitalOcean (Jboss and Oracle xe installed locally). Running everything on my dev machine I have no problem at all and it starts in about 30s, but...

Hibernate : Stale state exception


java,spring,hibernate,spring-mvc,transactions
I am working on a Spring-MVC application in which I am trying to delete an object from the database. Some days back, this error all of a sudden started, and now I am unable to delete. I checked on net, but I cannot find what am I doing wrong and...

Postgres SQL constraint a character type


postgresql,constraints
I have a table definition in Postgres. I would like to add a constraint to a column that is of Character datatype to have only 3 allowed values: CREATE TABLE my_table ( id character varying(255) NOT NULL, uid character varying(255) NOT NULL, my_text text NOT NULL, is_enabled boolean NOT NULL...

Subtract two columns of different tables


sql,postgresql,sum,aggregate-functions,subtract
I have two unrelated tables: contribution(id,amount, create_at, user_id) solicitude(id, amount, create_at, status_id, type_id, user_id) I need to subtract the sum of the amount of the contribution and of the solicitude from a user, but that result can't to be negative. How can I do this? Function or query? I tried...

How to order SQL query result on condition?


sql,postgresql,order,condition
i have the this SQL query: SELECT DISTINCT category FROM merchant ORDER BY category ASC that gives this output: accommodation education food general health money shopping sport transport How to put the row that contains "general" at the start (or the end) of the result?...

Return integer value of age(date) function in Postgres


postgresql
I would like to determine the number of days that an account has been open. Ideally, I would like to compare the return value to an integer(days). i.e I would like to see if age(open_date) > 14 If anyone has any better ideas... Thanks...

Save a hex-string to PostgreSQL column character varying


postgresql,hex
I want to save hex-string ('A2-5A-47-00-10-00-00-00') into a PostgeSQL database. My column is character varying(30). How can I do this?...

Retrieve updated rows in AFTER UPDATE trigger Postgresql


postgresql,triggers,plpgsql
I'm writing a AFTER UPDATE trigger in postgresql. Actualy I need to get at least one row after update in STATEMENT LEVEL trigger, but there is no OLD or NEW variable there. In FOR EACH ROW trigger I didn't manage to find a sort of batch_last param. But to do...

Can't Override Equals method on Java when calling contains


java,spring,hibernate
I have the following funtion that checks if a List of codigos contains a single codigos object: if (!concorrente.getJcodigoses().contains(cod)) { return "redirect:" + referrer; } I read that i need to Override the equals method like so: @Override public boolean equals(Object object) { boolean isEqual= false; if (object != null...

PostgreSQL: trigger to call function with parameters


postgresql
In PostgreSQL, I'm trying to create a trigger that passes an argument to a function, but it appears that this operation looks for a function whose signature has zero arguments: ERROR: function create_rec_if_needed() does not exist: CREATE TRIGGER after_update_winks AFTER UPDATE ON winks FOR EACH ROW WHEN (NEW.counter > 3)...

How to install / use orafce package in postgresql 9.4?


postgresql,debian,orafce
I'm running the "official" docker container of postgresql in version 9.4. I went inside the running container and installed orafce docker exec -i -t my_postgres bash apt-get install postgresql-9.4-orafce afterwards I've tried to reload and restart the postgresql service, as well as just restarting the whole container, but when I...

postgresql mathematical formula error


postgresql
Hi I am trying to use a mathematical function on each row in postgresql. But It gives me a error. My Query: Select stock_inventory_line.product_code AS Sku, COUNT(sale_order_line.name) AS Qty_Sold, stock_inventory_line.product_qty AS Current_Qty, (stock_inventory_line.product_qty / Qty_Sold) AS NOM From sale_order_line, product_product, product_template, product_category, stock_inventory_line WHERE sale_order_line.product_id = product_product.id AND product_product.product_tmpl_id =...

name of value returned from PostgreSQL function


postgresql,plpgsql
I'm working on some code that talks to a PostgreSQL server for the first time (my experience is with SQL Server) and I need help figuring something out. I've always tried to avoid "SELECT * ..." from code, but I can't figure out what the alternative is when calling a...

what is the SQL prepared stament for lo_import in postgreSQL


c++,sql,database,postgresql,odbc
In postgreSQL we have option to import the file into database using lo_import method, which returns a OID using that we can export the file from database to the filesystem. eg: describe test table name text, file_id oid insert into test values('arul_test',lo_import('/home/arul/test.txt')); prepared statement would be insert into test values(?,?);...

How to get second row in PostgreSQL?


sql,postgresql
I have next table: COLUMN_NAME DATA_TYPE PK NULLABLE inc_id bigint YES NO dt_cr timestamp NO NO email varchar(255) NO YES email column is not unique, so I should use GROUP BY email. Question: How can I get from this table minimal date, next row after minimal date and email related...

Postgresql Update JDBC


java,postgresql,jdbc
I want to update table: id integer NOT NULL, "first" character varying(255), "last" character varying(255), age integer, CONSTRAINT registration_pkey PRIMARY KEY (id) using method: void updateTable(String tableName, String columnName, String value, String columnName2, String value2) { try { String sql = "UPDATE " + tableName + " SET " +...

could not resolve property: userId.username


java,hibernate,criteria
I have following entity classes: @MappedSuperclass public class AbstractEntity implements Serializable, Comparable<AbstractEntity> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") protected Integer id; @Override public int compareTo(AbstractEntity o) { return this.toString().compareTo(o.toString()); } public Integer getId() { return id; } public...

Translation of interval


postgresql,datetime,translation,intervals,postgresql-8.4
There is maybe a way to translate automatically interval as it's shown by postgresql (e.g. "1330 days 10:54:54.266684") to other languages? For instance using locales, or other settings or I have to use replace, e.g. regexp_replace((now()-t.another_date)::text, 'day','dzień')?

How to create a SELECT query FROM “TABLE1 AND TABLE2”


sql,postgresql,select,join
I have a PostgreSQL database, with only SELECT permissions. In this DB there are two tables with the same structure (the same columns). I need to write several query in each table and join the results. There is a way for writing a query like this one? SELECT field1, field2,...

group by is not working in postgreSQL


sql,postgresql,group-by
I want group my data by createdAt but it is not working I don't know why... Only group by id which is useless for me. This is working: SELECT "id", "createdAt", "updatedAt" FROM "tables" AS "Table" WHERE "Table"."createdAt" BETWEEN '2014-04-21 20:46:25.938-04' AND '2015-04-21 20:46:25.938-04' GROUP BY "id"; This is what...

Is there a better way to write this query involving a self select?


sql,postgresql,join,aggregate-functions
I am looking for a "better" way to perform a query in which I want to show a single player who he has played previously and the associated win-loss record for each such opponent. Here are the tables involved stripped down to essentials: create table player (player_id int, username text);...

what is gradle missing to map hibernate?


java,hibernate,gradle
I have unittest to my java project. My code uses hibernate. When i run the test using junit - everything passes. When I run the test using gradle - I get a mapping error: Caused by: org.hibernate.MappingException: Unknown entity: linqmap.users.interfaces.model.UserRecord and the class: @Entity @Table(name = "users") public class UserRecord...

Bean Creation exception, Injection of autowired dependency failed


java,spring,hibernate,spring-mvc
I'm using spring hibernate in my application. I used all the required jar files but still getting bean creation exception saying the following: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'voteController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mindtree.service.VoteService com.mindtree.controller.VoteController.voteService; nested exception is...

How to customize the configuration file of the official PostgreSQL docker image?


postgresql,docker
I'm using the the postgres official image https://registry.hub.docker.com/_/postgres/. And now I'm trying to customize its configuration. For this purpose the command sed is used, e.g. to change the max_connections: sed -i -e"s/^max_connections = 100.*$/max_connections = 1000/" /var/lib/postgresql/data/postgresql.conf I tried two methods to apply this configuration. The first is by adding...

Is there a better solution to join the same dataset to get the distinct count of a dimension used for aggregation?


sql,postgresql
I have to do an aggregation on certain measures, but i also have to say how much distinct values i have for a dimension, which i use for aggregation. I can solve the problem using two sub-selects, but performance is not the best. Is there any way to solve this...

Redirect if ActiveRecord::RecordNotUnique error exists


ruby-on-rails,postgresql,activerecord,error-handling
I have the next code to save: Transaction.create(:status => params[:st], :transaction_id => params[:tx], :purchased_at => Time.now).save! But how can I redirect to main root page if this ActiveRecord::RecordNotUnique error appears? Can I catch this error?...

Hibernate criteria accepting %% value


java,hibernate,java-ee,orm,hibernate-criteria
I am using the below Hibernate code to filter workFlowName. crt.add(Restrictions.like("workFlowName", workFlow, MatchMode.ANYWHERE)); // crt is the criteria The problem is when I pass the value to workFlow from web (TextBox).it fetching the value correctly (I am passing sym in text box if fetch 10 records.if i pass the same...

JSONB: more than one row returned by a subquery used as an expression


sql,postgresql,postgresql-9.4,jsonb,set-returning-functions
I am (still) new to postgresql and jsonb. I am trying to select some records from a subquery and am stuck. My data column looks like this (jsonb): {"people": [{"age": "50", "name": "Bob"}], "another_key": "no"} {"people": [{"age": "73", "name": "Bob"}], "another_key": "yes"} And here is my query. I want to...

PostgreSQL can't find column


java,postgresql
I create a database that contains 4 column (ID_PRODUIT,NOM_PRODUIT,QUANTITE, PRIX).I tried to make a methods that allow me to serach Product(my class)using a string key,however, the query failed to identify the "NOM_PRODUIT" column and it turn "NOM_PRODUIT" to "nom_produit" in the messsage error. Connection conn = DriverManager.getConnection(url, user, passwd); PreparedStatement...

Spring Boot - How to set the default schema for PostgreSQL?


java,spring,hibernate,postgresql
What I am currently doing in my application.properties file is: spring.datasource.url=jdbc:postgresql://localhost:5432/myDB?currentSchema=mySchema Isn't there another property for this? Since it looks hacky and according to a post (still finding the link sorry, will update later), it is only applicable to PostgreSQL 9.4....

How to call MySQL view in Struts2 or Hibernate


java,mysql,hibernate,java-ee,struts2
I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

Error while trying to insert data using plpgsql


postgresql,timestamp,plpgsql
I have the following plpgsql function: CREATE OR REPLACE FUNCTION test_func(OUT pid bigint) RETURNS bigint AS $BODY$ DECLARE current_time timestamp with time zone = now(); BEGIN INSERT INTO "TEST"( created) VALUES (current_time) RETURNING id INTO pid; END $BODY$ LANGUAGE plpgsql; select * from test_func(); The above gives an error: column...

Syntax error while creating table in PostgreSQL 8.1


postgresql
I have a syntax error in this query: CREATE TABLE test (LIKE original_table INCLUDING INDEXES); ERROR : syntax error at or near "INDEXES" I am using PostgreSQL 8.1 version. Where is the issue in my query?...