简体   繁体   中英

Auto-increment not created

domain class

package testgrails12

class Teams {
    Integer id
    String name
    static mapping = {
        table 'teams'
        version false
        name column: 'name', sqlType: 'VARCHAR(200)'
        id generator: 'increment',
                params: [table:'teams', column: 'idteam', sqlType: 'INT(10)', updateable: false, insertable: false]
        /*id column: 'idteam', sqlType: 'INT(11)', updateable: false, insertable: false,
                generator: 'increment'*/
    }
    static constraints = {
        name nullable: true
    }
}

This class creates a table img I need to create a table with a field id auto incremental. Help me whith mapping.

If you're using Grails and you're happy with the primary key named id you don't need to specify any of the info you've specified. Grails will take care of the auto-increment strategy based on your underlying DB.

Again if you're happy with the table name team you don't need to add anything to mapping related to this.

You've specified you're okay having a null name which may not be correct as you'll end up with rows with just a primary key.

You should also go with a non-pluralised name for your table ie team.

package testgrails12

    class Team {

    String name

    static mapping = {
        version false
    }

    static constraints = {
        name nullable: true
    }
}

In you mapping file you need to add generator like this.

<hibernate-mapping>  
  <class ...>  
    <id ...>  
     <generator class="increment"></generator>  
    </id>  

    .....  

  </class>  
 </hibernate-mapping> 

above you have to do mapping for id like this only. Because in Hibernate default generator is assigned . So you need to add your generator.

If you want to use Annotation in class than you need to add those annotation with you id property.

@Id  
@GeneratedValue(strategy=GenerationType.AUTO)  
private int id; 

Here strategy=GenerationType.AUTO it will make id column to Auto Increment .

If you are using annotation then below code snippet might help you:

@Id @GeneratedValue(strategy=GenerationType.AUTO) 
OR 
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) // both are the same thing
    @Column(name = "Id", unique = true, nullable = false)
    public Long getId() {
        return this.Id;
    }

    public void setId(Long Id) {
        this.Id = Id;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM