93 lines
2.2 KiB
Markdown
93 lines
2.2 KiB
Markdown
---
|
|
aliases:
|
|
- entity beans
|
|
---
|
|
up:: [[Enterprise Java Beans]]
|
|
#s/informatique/langage/java
|
|
|
|
> [!definition] Définition
|
|
> Un entity bean est un [[Enterprise Java Beans|EJB]] qui matérialise des données pour qu'elles soient manipulables par des [[EJB session beans|session beans]].
|
|
> Les entity bean sont responsables de la liaison entre la couche business et la couche données ([[modèle OSI]])
|
|
> Le plus souvent, un entity bean représente une ligne ou une table d'une base de données.
|
|
^definition
|
|
|
|
```breadcrumbs
|
|
title: "Sous-notes"
|
|
type: tree
|
|
collapse: false
|
|
show-attributes: [field]
|
|
field-groups: [downs]
|
|
depth: [0, 0]
|
|
```
|
|
|
|
|
|
# Exemples
|
|
|
|
## Livre
|
|
```java
|
|
@Entity
|
|
public class Book {
|
|
@Id @GeneratedValue
|
|
private Long id;
|
|
@Column(nullable = false)
|
|
private String title;
|
|
private Float price;
|
|
@Column(length = 2000)
|
|
private String description;
|
|
private String isbn;
|
|
private Integer obOfPage;
|
|
private Boolean illustrations;
|
|
|
|
// constructeur, getters et setters
|
|
}
|
|
```
|
|
|
|
Exemple d'insertion d'un nouveau livre :
|
|
```java
|
|
public class Main {
|
|
public static void main(String[] args) {
|
|
// créer une instance de livre :
|
|
Book book = new Book();
|
|
book.setTitle("The Hitchhiker's Guide to the Galaxy");
|
|
book.setPrice(12.5F);
|
|
book.setDescription("Science fiction comedy book");
|
|
|
|
// récupérer un pointer sur l'entity manager :
|
|
EntityManagerFactory enf =
|
|
Persistence.createEntityManagerFactory("chapter02PU");
|
|
EntityManager em = emf.createEntityManager();
|
|
|
|
// rendre l'objet persistant
|
|
EntityTransaction tx = em.getTransaction();
|
|
tx.begin();
|
|
em.persist(book);
|
|
tx.commit();
|
|
|
|
em.close();
|
|
emf.close()
|
|
}
|
|
}
|
|
```
|
|
|
|
### Depuis un [[EJB session beans|session bean]]
|
|
```java
|
|
@Stateless
|
|
public class UnSessionBean {
|
|
@PersistenceContext(unitName="EmployeeService")
|
|
EntityManager em;
|
|
|
|
public Book createBook(String titre,...) {
|
|
// instancier le livre
|
|
Book book = new Book();
|
|
book.setTitle(...);
|
|
...
|
|
|
|
// rendre le livre persistant
|
|
em.persist(book);
|
|
return book;
|
|
}
|
|
}
|
|
```
|
|
|
|
|