Java 泛型。对我来说有什么好处?

发布于 2024-12-29 00:59:52 字数 2416 浏览 4 评论 0原文

现在我开始开发基于MVC的小型Web应用程序。 现在我尝试使用 DAO 模式实现模型布局的主类。

因此,首先我创建两个实体类(例如):Author 和 Book:

package myProject.model.entity;

import java.io.Serializable;

    public class Author implements Serializable {

        private static final long serialVersionUID = 7177014660621405534L;

        private long id;
        private String firstName;
        private String lastName;

        public Author() {       
        }
    // getter and setter methods here

    }

以及 Book 类:

  package myProject.model.entity;

    import java.io.Serializable;

        public class Book implements Serializable {

            private static final long serialVersionUID = 7177014660621405534L;

            private long id;
            private String title;
            private String description;

            public Book() {     
            }
        // getter and setter methods here

        }

在下一步中,我看到 Book 和 Author 类都有 getId()setId()。 所以,我为我的实体类创建接口Persistent

 package myProject.model.entity;

        public interface Persistent {

                public long getId();
                public void setId(long id); 


        }

所以,首先我的问题:

它是model包的正确实现吗?

下一步,我开始为 dao 包实现类。

package myProject.model.dao;

import java.util.List;

import myProject.model.entity.Persistent;

public interface Dao {

    Persistent get(long id);

    void save(Persistent persistent);

    void delete(long id);
}

下一步:创建接口 AuthorDaoBookDao,扩展基础 dao interface Dao

但这两个接口:AuthorDao 和 BookDao - 目前都是空的。 您认为正常情况下,接口是空的吗?这是我的第二个问题。

在最后一步中,我创建包 model.dao.hibernate 并将其添加到类 AuthorDaoHibernate 和 BookDaoHibernate - 这两个类都实现 AuthorDao 和 BookDao 接口。

现在我的主要问题:

我的接口 Dao 使用对象类型 Persistent 并且我不使用泛型。一切都很好。

你觉得怎么样 - 如果我用泛型重新设计 Dao 接口,我会有什么好处:

package myProject.model.dao;

import java.util.List;

import myProject.model.entity.Persistent;

public interface Dao<Persistent> {

    T get(long id);

    List<T> getAll();

    void save(T persistent);

    void delete(long id);
}

我的 Dao 类仅适用于持久实体 - 没有任何其他对象类型......

你真的有什么理由吗?我的情况使用泛型?

At this moment I start work on small web application based on MVC.
Now I try implement main classes for Model layout using DAO pattern.

So, first of all I create two entity classes (for example): Author and Book:

package myProject.model.entity;

import java.io.Serializable;

    public class Author implements Serializable {

        private static final long serialVersionUID = 7177014660621405534L;

        private long id;
        private String firstName;
        private String lastName;

        public Author() {       
        }
    // getter and setter methods here

    }

and Book class:

  package myProject.model.entity;

    import java.io.Serializable;

        public class Book implements Serializable {

            private static final long serialVersionUID = 7177014660621405534L;

            private long id;
            private String title;
            private String description;

            public Book() {     
            }
        // getter and setter methods here

        }

On next step, I see, that classes Book and Author both have getId() and setId().
so, I create interface Persistent for my Entity classes:

 package myProject.model.entity;

        public interface Persistent {

                public long getId();
                public void setId(long id); 


        }

So, first my question:

It is correct implementation for model package?

On the next step, I start implement classes for package dao.

package myProject.model.dao;

import java.util.List;

import myProject.model.entity.Persistent;

public interface Dao {

    Persistent get(long id);

    void save(Persistent persistent);

    void delete(long id);
}

Next step: create interfaces AuthorDao and BookDao, that extend base dao interface Dao

But both interfaces: AuthorDao and BookDao - at this moment empty.
What do you think - it in normal, that interfaces empty? It is my second question.

And on the last step I create package model.dao.hibernate and add to the package to class AuthorDaoHibernate and BookDaoHibernate - both class implements AuthorDao and BookDao interfaces.

And My main question now:

my interface Dao work with objects type Persistent and I dont use Generics. And all ok and nice.

What do you thinks - what benefits I have, if I re-work Dao interface wit Generics:

package myProject.model.dao;

import java.util.List;

import myProject.model.entity.Persistent;

public interface Dao<Persistent> {

    T get(long id);

    List<T> getAll();

    void save(T persistent);

    void delete(long id);
}

My Dao classes work only with persistent entities - no any other object type...

Do you really any reasons in me case use Generics?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寄风 2025-01-05 00:59:52

泛型可以极大地提高代码的可读性并减少错误转换可能导致的错误。

我们正在使用与您所描述的类似的东西(请注意,需要接口实现)。

这是一个基本示例(为了简洁起见,我将保留 getter 和 setter):

@MappedSuperClass
class BaseEntity {
  @Id
  private int id;
}

@Entity
class UserEnity extends BaseEntity {
  //user stuff like name
}

class BaseDAO<T extends BaseEntity> {
  public T findById(int id) { 
    ... 
  }
  //other generic CRUD methods
}

@Stateless
class UserDAO extends BaseDAO<UserEntity> {
  //additional user specific methods
}

然后使用 UserDAO 将如下所示:

 UserDAO userDao; //some injection or lookup

 //no explicit cast needed here, thanks to generics
 UserEntity user = userDao.findById(userId);

 //compiler error due to the generic parameter being UserEntity and AnotherEntity doesn't extend that
 AnotherEntity a = userDao.findById(someId);

Generics can greatly improve code readability and reduce errors that could come from wrong casting.

We're using something similar to what you described (note that there are interfaces and implementations needed).

Here's a basic example (I'll leave the getters and setters out for brevitiy):

@MappedSuperClass
class BaseEntity {
  @Id
  private int id;
}

@Entity
class UserEnity extends BaseEntity {
  //user stuff like name
}

class BaseDAO<T extends BaseEntity> {
  public T findById(int id) { 
    ... 
  }
  //other generic CRUD methods
}

@Stateless
class UserDAO extends BaseDAO<UserEntity> {
  //additional user specific methods
}

Using UserDAO would then be like this:

 UserDAO userDao; //some injection or lookup

 //no explicit cast needed here, thanks to generics
 UserEntity user = userDao.findById(userId);

 //compiler error due to the generic parameter being UserEntity and AnotherEntity doesn't extend that
 AnotherEntity a = userDao.findById(someId);
苦笑流年记忆 2025-01-05 00:59:52

如果您想使用泛型,您应该按如下方式定义 Dao:

public interface Dao<T extends Persistent> {
    .....................
    void save(T persistent);
    ...................
}

现在,当您扩展它时,您必须创建仅接受 Book 的保存:

public class Book extends Dao<Book> {
    .....................
    void save(Book persistent);
    ...................
}

这里的好处是您无法将 Author 传递给 BookDao。这不会通过编译。

顺便说一句,如果您使用 Hibernate、JPA 或其他 ORM 解决方案,您实际上不必为每个实体创建 DAO。一个通用的 dao 可以解决您的所有需求。

If you want to use generics you should define Dao as following:

public interface Dao<T extends Persistent> {
    .....................
    void save(T persistent);
    ...................
}

Now when you extend it you will have to create save that accepts Book only:

public class Book extends Dao<Book> {
    .....................
    void save(Book persistent);
    ...................
}

The benefit here is that you cannot pass Author to BookDao. This will not pass compilation.

BTW if you are using Hibernate, JPA or other ORM solution you do not really have to create DAO per entity. One generic dao can solve all your needs.

殤城〤 2025-01-05 00:59:52

这里没有理由。如果它是独特的,那么根据定义它就不是通用的!
List getAll() 将完成这项工作。

ArrayList 是通用的,因为它有时会返回 Persistent,有时会返回 President。

There is no reason here. If it's unique, it's not generic, by definition !
List getAll() will do the Job.

The ArrayList is Generic because it will sometimes return Persistent, sometime President.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文