1. Implementation description
When we write programs, we often encounter this problem:
Insert a data, but because of the existence of the primary key, an error of "violating uniqueness constraints" will sometimes be reported.
Next, let’s use MyBatis to solve this problem.
2. The database used in this article is MySQL
If you need to use other databases, please make appropriate changes.
3. Self-increase according to the primary key
Configure implementation in MyBatis, as follows:
<insert parameterType="role" useGeneratedKeys="true" keyProperty="id"> insert into t_role(role_name,note) values (#{roleName},#{note}) </insert>
Analysis:
1. We use the keyProperty attribute to specify id as the primary key field, and use the useGeneratedKeys attribute to tell MyBatis whether the primary key is generated using the built-in rules of the database.
2. The auto-increment rule for id is set in the database, as shown below:
mysql>alter table t_role change id id int primary key auto_increment;
3. In the above configuration, we specify the id column as the self-increment field, so we establish a POJO. In this way, use the primary key backfill function of MyBatis to achieve the correct insertion operation (no need to set the id value, MyBatis will be processed with the database settings).
4. Test:
sqlSession = (); RoleMapper roleMapper = (); Role role = new Role(); ("test4"); ("test4Note"); (role); (());
4. Custom primary key generation rules implementation
Examples are as follows:
<insert parameterType="role" useGeneratedKeys="true" keyProperty="id"> <selectKey keyProperty="id" resultTyle="int" order="BEFORE"> select if(max(id) is null, 1, max(id) + 2) as newId from t_role </selectKey> insert into t_role(id,role_name,note) values(#{id},#{roleName},#{note}); </insert>
Analysis:
The configuration that defines the self-increment rule for MyBatis is shown above. In fact, the selectKey configuration above is similar to the trigger in the database. Order="BEFORE" specifies that the search for newId is executed before the statement is executed, and then the insert statement is executed.
In this way, we use custom primary key rules to increase data.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.