TopDev

viết code java Hibernate JSF thêm tin tức

minhdev 📖 2 phút đọc

Dưới đây là một ví dụ cơ bản về cách sử dụng Hibernate và JSF để xây dựng chức năng thêm tin tức và mỗi tin vào nhiều chuyên mục với cơ sở dữ liệu Oracle.

1. Cấu trúc cơ sở dữ liệu#

` CREATE TABLE CATEGORY ( ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, NAME VARCHAR2(100) NOT NULL );

CREATE TABLE NEWS ( ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, TITLE VARCHAR2(200) NOT NULL, CONTENT CLOB NOT NULL );

CREATE TABLE NEWS_CATEGORY ( NEWS_ID NUMBER, CATEGORY_ID NUMBER, CONSTRAINT FK_NEWS FOREIGN KEY (NEWS_ID) REFERENCES NEWS(ID), CONSTRAINT FK_CATEGORY FOREIGN KEY (CATEGORY_ID) REFERENCES CATEGORY(ID), PRIMARY KEY (NEWS_ID, CATEGORY_ID) ); `

2. Entity Classes#

News.java

` import jakarta.persistence.*; import java.util.Set;

@Entity @Table(name = "NEWS") public class News { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

private String title;

@Lob
private String content;

@ManyToMany
@JoinTable(
    name = "NEWS_CATEGORY",
    joinColumns = @JoinColumn(name = "NEWS_ID"),
    inverseJoinColumns = @JoinColumn(name = "CATEGORY_ID")
)
private Set<Category> categories;

// Getters and Setters

} `

Category.java

` import jakarta.persistence.*; import java.util.Set;

@Entity @Table(name = "CATEGORY") public class Category { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

private String name;

@ManyToMany(mappedBy = "categories")
private Set<News> news;

// Getters and Setters

} `

3. Managed Bean cho JSF#

NewsBean.java

` import jakarta.enterprise.context.RequestScoped; import jakarta.inject.Named; import jakarta.transaction.Transactional; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext;

import java.util.List;

@Named @RequestScoped public class NewsBean { @PersistenceContext private EntityManager entityManager;

private News news = new News();
private List<Long> selectedCategoryIds;

public List<Category> getAllCategories() {
    return entityManager.createQuery("SELECT c FROM Category c", Category.class).getResultList();
}

@Transactional
public String addNews() {
    List<Category> categories = entityManager.createQuery(
        "SELECT c FROM Category c WHERE c.id IN :ids", Category.class)
        .setParameter("ids", selectedCategoryIds)
        .getResultList();

    news.setCategories(Set.copyOf(categories));
    entityManager.persist(news);

    return "newsList.xhtml?faces-redirect=true";
}

// Getters and Setters
public News getNews() {
    return news;
}

public void setNews(News news) {
    this.news = news;
}

public List<Long> getSelectedCategoryIds() {
    return selectedCategoryIds;
}

public void setSelectedCategoryIds(List<Long> selectedCategoryIds) {
    this.selectedCategoryIds = selectedCategoryIds;
}

} `

4. Giao diện JSF#

addNews.xhtml

`

Thêm Tin Tức
    <h:outputLabel value="Nội dung:" for="content" />
    <h:inputTextarea id="content" value="#{newsBean.news.content}" />

    <h:outputLabel value="Chuyên mục:" />
    <h:selectManyCheckbox value="#{newsBean.selectedCategoryIds}">
        <f:selectItems value="#{newsBean.allCategories}" var="category"
                       itemValue="#{category.id}" itemLabel="#{category.name}" />
    </h:selectManyCheckbox>

    <h:commandButton value="Thêm" action="#{newsBean.addNews}" />
</h:form>

`

5. Cấu hình persistence.xml#

<persistence xmlns="http://jakarta.ee/xml/ns/persistence" version="3.0"> <persistence-unit name="default"> <class>com.example.News</class> <class>com.example.Category</class> <properties> <property name="jakarta.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" /> <property name="jakarta.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:orcl" /> <property name="jakarta.persistence.jdbc.user" value="your_username" /> <property name="jakarta.persistence.jdbc.password" value="your_password" /> <property name="jakarta.persistence.schema-generation.database.action" value="update" /> </properties> </persistence-unit> </persistence>

6. Hướng dẫn chạy#

  • Tạo cơ sở dữ liệu theo cấu trúc đã cung cấp.

  • Cấu hình persistence.xml với thông tin kết nối Oracle.

  • Triển khai ứng dụng lên một container hỗ trợ Jakarta EE (như WildFly hoặc Payara).

  • Truy cập giao diện addNews.xhtml và thử thêm tin tức vào các chuyên mục.

Bài liên quan trong #Java

✓ Đã sao chép link