Hibernate Named Query tutorial with example annotation based


Named Query Annotation based


Queries can also be configured as so called named queries using annotations or Hibernate mapping documents. @NamedQuery and @NamedQueries can be defined at the class level


@NamedQueries({ @NamedQuery(name = "name", query = "from User where username = :un") })

Code


User.java

package com.candidjava.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@NamedQueries({ @NamedQuery(name = "name", query = "from User where username = :un") })
@Entity
@Table(name = "login")
public class User {
	@Id
	@GeneratedValue
	@Column(name = "id")
	private int id;
	@Column(name = "username")
	private String username;
	@Column(name = "password")
	private String password;

	@GeneratedValue(strategy = GenerationType.AUTO)
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

Get or fetch record using Named Query
public User getByUsername(String name) {
		Session session = getSession();
		User user = (User) session.getNamedQuery("name").setString("un", name)
				.uniqueResult();
		return user;
	}

Download

Hibernate Named Query Annotation war

Hibernate Named Query zip





Related Post

Comments


©candidjava.com