# @ManyToOne Relacionamento N:1

Exemplificando a criação de um relacionamento N:1, utilizando as anotações do Framework.

![Relacionamento N:1](https://750641972-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MHGW_meLjEK-3soe8kP%2F-MJr6yI5dH1-XQomAulx%2F-MJrQGS2FlEoDY7U5Zok%2FClass-Diagram.png?alt=media\&token=5e5e6f1c-4cd6-480b-8d3b-50c1e7400eb5)

A anotação @ManyToOne representará o relacionamento na classe Produto. Segue a implementação das classes persistentes:

**Classe Persistente Categoria**

```java
package br.com.rel.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="tb_categoria")
public class Categoria {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Integer id;
	private String nome;
	private String descricao;

	public Categoria() {

	}
        // Gerar Gets e Sets
}
```

&#x20;**Classe Persistente Produto**

```java
package br.com.rel.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
@Table(name="tb_produto")
public class Produto {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Integer id;
	private String nome;
	private String descricao;
	private String fabricante;
	private Integer quantidade;
	private Double valorUnitario;

	@ManyToOne(fetch=FetchType.EAGER)
	@JoinColumn(name="id_categoria", insertable=true, updatable=true)
	@Fetch(FetchMode.SELECT)
	@Cascade(CascadeType.SAVE_UPDATE)
	private Categoria categoria;

	public Produto() {

	}
        // Gerar Gets e Sets
}
```

&#x20;Na classe Produto criamos um objeto do tipo categoria que será responsável pelo mapeamento do relacionamento neste objeto fazemos as seguintes anotações:&#x20;

**@ManyToOne(fetch= FetchType.EAGER)** que representa em sim o relacionamento do tipo N para 1, já o atributo **fetch** com valor **FetchType.EAGER** significa que toda vez que o objeto pai for recuperado da base o atributo mapeado também será recuperado;&#x20;

**@JoinColumn** é usada para informar qual o nome da coluna que corresponde à chave estrangeira do mapeamento os atributos  **insertable** e **updatable** que se assumirem true indica que o atributo deve ser inserido  ou atualizado;&#x20;

**@Fecth** vai definir como o atributo mapeado será recuperado da base, no nosso caso é feito um **SELECT** para recuperar o atributo. E assim conseguimos mapear o relacionamento N para 1


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pauloricmarinho.gitbook.io/desenvolvimento/java/hibernate-framework/manytoone-relacionamento-n-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
