猿问

如何查询 mysql 数据库中的特定实体

我想弄清楚如何查询 mysql 数据库中的特定歌曲。我的想法是通过 ID 查找歌曲,因此如果我传递 ID,一首歌曲应该出现在浏览器窗口中。


public class Song {


private int id = 0;

private String title;

private String artist;

private String album;

private int released;


public Song() {

}


public Song(int id, String title, String artist, String album, int released) {

    this.id = id;

    this.title = title;

    this.artist = artist;

    this.album = album;

    this.released = released;

}

@Id

@Column(name = "songID")

@GeneratedValue(strategy = GenerationType.IDENTITY)

public Integer getId() {

    return id;

}

SongWebService.java


    @GET

    @Path("/{id}")

    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })

public Response getSongById() { 


    Object song = null;

    try {

        em.getTransaction().begin();            

        song = em.createQuery("SELECT s FROM Song s WHERE s.songID = :id", Song.class).getSingleResult();

        em.getTransaction().commit(); 

    } catch (NoResultException e) {

        Response.noContent().build();

    } catch (Exception ex) {

        ex.printStackTrace();

        em.getTransaction().rollback();

    } finally {

        em.close();

    }

    return Response.ok(song).build();

}


千万里不及你
浏览 110回答 1
1回答

慕雪6442864

创建一个查询对象并设置参数值,然后获取单行TypedQuery<Song> query =&nbsp; em.createQuery("SELECT s FROM Song s WHERE s.songID = :id", Song.class);query.setParameter(1, id); //not sure what id&nbsp;Song song = query.getSingleResult();
随时随地看视频慕课网APP

相关分类

Java
我要回答