Grails save() Domain Object actually does a Select

2019-02-25 13:23发布

问题:

I am trying to take a JSONObject I posted to my groovy controller. I can pass the object, see the JSON data and then create a Domain Object out of it. When I save it to write to the database it does a Select instead.

def save = {
    def input = request.JSON
    def instance = new Customers(input)
    instance.save()
}   

here is my debug sql output

Hibernate: 
select
    this_.customers_id as customers1_237_0_,
    this_.customers_default_address_id as customers2_237_0_,
    this_.customers_dob as customers3_237_0_,
    this_.customers_email_address as customers4_237_0_,
    this_.customers_email_address2 as customers5_237_0_,
    this_.customers_fax as customers6_237_0_,
    this_.customers_firstname as customers7_237_0_,
    this_.customers_gender as customers8_237_0_,
    this_.customers_lastname as customers9_237_0_,
    this_.customers_membertype as customers10_237_0_,
    this_.customers_memo1 as customers11_237_0_,
    this_.customers_mname as customers12_237_0_,
    this_.customers_newsletter as customers13_237_0_,
    this_.customers_password as customers14_237_0_,
    this_.customers_point_date as customers15_237_0_,
    this_.customers_telephone as customers16_237_0_,
    this_.customers_total_points as customers17_237_0_,
    this_.customers_username as customers18_237_0_ 
from
    customers this_ 
where
    this_.customers_username=?

Don't know what would be causing this.

回答1:

Looks like you have a unique constraint on username. Grails does a select to check uniqueness since assumed that reading one row is a lightweight action and it's preferable to triggering a unique constraint violation and exception.

An alternative is to remove the unique constraint in the domain class and add the unique constraint manually in the database.



回答2:

Did you tried something like :

Customers cust = new Customers(input);
println ("cust = "+cust);
cust.save();