CRUD Operations
Harry
· 11 Sep 2026
· 10 views
Select
<select id="findAll" resultType="Customer">
SELECT * FROM customers ORDER BY id
</select>Insert With Generated Keys
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO customers (name, email, city)
VALUES (#{name}, #{email}, #{city})
</insert>useGeneratedKeys + keyProperty writes the auto-generated key back into the Java object (Customer.getId() returns it).
Update and Delete
<update id="update">
UPDATE customers
SET name = #{name}, email = #{email}, city = #{city}
WHERE id = #{id}
</update>
<delete id="delete">
DELETE FROM customers WHERE id = #{id}
</delete>Returning the Affected Count
UPDATE and DELETE statements return the number of rows changed. Return int from the mapper method to read it:
int rows = mapper.update(customer); // 1 when a row was updatedFull CRUD Example
CustomerMapper mapper = session.getMapper(CustomerMapper.class);
mapper.insert(new Customer("Priya", "priya@example.com", "Mumbai"));
Customer c = mapper.findById(c.getId());
c.setCity("Pune");
mapper.update(c);
int deleted = mapper.delete(c.getId());Key Points
- Select, insert, update, delete map to the four mapper statement tags.
- useGeneratedKeys retrieves auto-increment IDs into the entity.
- Updates/deletes return the number of affected rows.
- #{} parameters are always bound safely.