简体   繁体   中英

How do you do a generic insert with JDBI?

I am using JDBI with MySQL and I've an interface GenericDao where I've this method

public void insert(T entity);

How do I implement this method with JDBI by using the fluent queries instead of SQLObjects?

Is it possible to use either of this?

handle.insert

or

handle.createQuery 

I found that SQLObjects worked nice for me when I used SQLObjects style:

public interface GenericDao<T> {
    List<T> findAll();
    long insert(T t);
    long update(T t);
    long delete(long id);
    T findNameById(long id);
}

I then used an abstract class for putting in all the SQL

@RegisterMapper(VesselJDBIMapper.class)
public abstract class VesselJDBI implements Transactional<VesselJDBI>, GenericDao<Vessel> {

    @SqlUpdate("UPDATE vessel SET vessel_name = :vesselName, version = version +1 WHERE vessel_id = :id" +
            " AND version = :version")
    public abstract long update(@BindBean Vessel vessel);

    @SqlUpdate("DELETE FROM vessel WHERE vessel_id = :id")
    public abstract long delete(@Bind("id") long id);

    @SqlQuery("SELECT vessel_id, vessel_name, version FROM vessel WHERE vessel_id = :id")
    public abstract Vessel findNameById(@Bind("id") long id);

    @SqlUpdate("INSERT INTO vessel (vessel_name, version) VALUES (:vesselName, :version)")
    @GetGeneratedKeys
    public abstract long insert(@BindBean Vessel vessel);

    @SqlQuery("SELECT vessel_id, vessel_name, version FROM vessel ORDER BY vessel_id")
    public abstract List<Vessel> findAll();
}

Maybe that will provide a solution for someone.

You can get handle by implementing GetHandle interface.

public abstract class GenericDao<T>  implements GetHandle {

    public void insert(T entity) {
        getHandle().insert("some sql");
    };

}

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