前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Hibernate学习笔记 查询简介

Hibernate学习笔记 查询简介

作者头像
乐百川
发布2022-05-05 19:35:52
3720
发布2022-05-05 19:35:52
举报

创建实体类

在介绍Hibernate查询语言之前,首先我们来建立一下数据库。这里直接使用了MySQL自带的样例数据库world。如果你没有安装MySQL那么需要安装一下,并且在安装的时候选择安装样例数据库。

安装完成之后,应该能在MySQL中看到一个名为world的数据库,其中有三个表,country、city以及countrylanguage表。然后我们来建立这三个表对应的实体类。需要注意,由于这一次是针对已经存在的数据库,所以在hibernate.cfg.xml<property name="hbm2ddl.auto">update</property>这一行应当设置为update,避免Hibernate重新创建表覆盖掉原有的数据。

这三个表有点长,所以会影响到阅读。由于countrylanguage表存在两个主键,而且Hibernate要求复合主键的实体类必须实现Serializable接口,所以这里也实现了这个接口。

代码语言:javascript
复制
@Entity
public class City {
    private int id;
    private Country country;
    private String district;
    private String name;
    private Integer population;

    @Id
    @Column(name = "ID")
    public int getId() {
        return id;
    }

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

    @ManyToOne
    @JoinColumn(name = "CountryCode", foreignKey = @ForeignKey(name = "countryLanguage_ibfk_1"))
    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }

    @Basic
    @Column(name = "District")
    public String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district;
    }

    @Basic
    @Column(name = "Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "Population")
    public Integer getPopulation() {
        return population;
    }

    public void setPopulation(Integer population) {
        this.population = population;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        City city = (City) o;
        return id == city.id &&
                Objects.equals(country, city.country) &&
                Objects.equals(district, city.district) &&
                Objects.equals(name, city.name) &&
                Objects.equals(population, city.population);
    }

    @Override
    public String toString() {
        return "City{" +
                "id=" + id +
                ", country=" + country.getName() +
                ", district='" + district + '\'' +
                ", name='" + name + '\'' +
                ", population=" + population +
                '}';
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, country, district, name, population);
    }
}



@Entity
public class Country {
    private String code;
    private String name;
    private String continent;
    private String region;
    private double surfaceArea;
    private Short indepYear;
    private int population;
    private Double lifeExpectancy;
    private Double gnp;
    private Double gnpOld;
    private String localName;
    private String governmentForm;
    private String headOfState;
    private Integer capital;
    private String code2;

    @Id
    @Column(name = "Code")
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Basic
    @Column(name = "Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "Continent")
    public String getContinent() {
        return continent;
    }

    public void setContinent(String continent) {
        this.continent = continent;
    }

    @Basic
    @Column(name = "Region")
    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    @Basic
    @Column(name = "SurfaceArea")
    public double getSurfaceArea() {
        return surfaceArea;
    }

    public void setSurfaceArea(double surfaceArea) {
        this.surfaceArea = surfaceArea;
    }

    @Basic
    @Column(name = "IndepYear")
    public Short getIndepYear() {
        return indepYear;
    }

    public void setIndepYear(Short indepYear) {
        this.indepYear = indepYear;
    }

    @Basic
    @Column(name = "Population")
    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Basic
    @Column(name = "LifeExpectancy")
    public Double getLifeExpectancy() {
        return lifeExpectancy;
    }

    public void setLifeExpectancy(Double lifeExpectancy) {
        this.lifeExpectancy = lifeExpectancy;
    }

    @Basic
    @Column(name = "GNP")
    public Double getGnp() {
        return gnp;
    }

    public void setGnp(Double gnp) {
        this.gnp = gnp;
    }

    @Basic
    @Column(name = "GNPOld")
    public Double getGnpOld() {
        return gnpOld;
    }

    public void setGnpOld(Double gnpOld) {
        this.gnpOld = gnpOld;
    }

    @Basic
    @Column(name = "LocalName")
    public String getLocalName() {
        return localName;
    }

    public void setLocalName(String localName) {
        this.localName = localName;
    }

    @Basic
    @Column(name = "GovernmentForm")
    public String getGovernmentForm() {
        return governmentForm;
    }

    public void setGovernmentForm(String governmentForm) {
        this.governmentForm = governmentForm;
    }

    @Basic
    @Column(name = "HeadOfState")
    public String getHeadOfState() {
        return headOfState;
    }

    public void setHeadOfState(String headOfState) {
        this.headOfState = headOfState;
    }

    @Basic
    @Column(name = "Capital")
    public Integer getCapital() {
        return capital;
    }

    public void setCapital(Integer capital) {
        this.capital = capital;
    }

    @Basic
    @Column(name = "Code2")
    public String getCode2() {
        return code2;
    }

    public void setCode2(String code2) {
        this.code2 = code2;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Country country = (Country) o;
        return Double.compare(country.surfaceArea, surfaceArea) == 0 &&
                population == country.population &&
                Objects.equals(code, country.code) &&
                Objects.equals(name, country.name) &&
                Objects.equals(continent, country.continent) &&
                Objects.equals(region, country.region) &&
                Objects.equals(indepYear, country.indepYear) &&
                Objects.equals(lifeExpectancy, country.lifeExpectancy) &&
                Objects.equals(gnp, country.gnp) &&
                Objects.equals(gnpOld, country.gnpOld) &&
                Objects.equals(localName, country.localName) &&
                Objects.equals(governmentForm, country.governmentForm) &&
                Objects.equals(headOfState, country.headOfState) &&
                Objects.equals(capital, country.capital) &&
                Objects.equals(code2, country.code2);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code, name, continent, region, surfaceArea, indepYear, population, lifeExpectancy, gnp, gnpOld, localName, governmentForm, headOfState, capital, code2);
    }

    @Override
    public String toString() {
        return "Country{" +
                "code='" + code + '\'' +
                ", name='" + name + '\'' +
                ", continent='" + continent + '\'' +
                ", region='" + region + '\'' +
                ", surfaceArea=" + surfaceArea +
                ", indepYear=" + indepYear +
                ", population=" + population +
                ", lifeExpectancy=" + lifeExpectancy +
                ", gnp=" + gnp +
                ", gnpOld=" + gnpOld +
                ", localName='" + localName + '\'' +
                ", governmentForm='" + governmentForm + '\'' +
                ", headOfState='" + headOfState + '\'' +
                ", capital=" + capital +
                ", code2='" + code2 + '\'' +
                '}';
    }
}



@Entity
public class Countrylanguage implements Serializable {
    private String language;
    private Country country;
    private String isOfficial;
    private Double percentage;

    @Id
    @Column(name = "Language")
    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    @Id
    @ManyToOne
    @JoinColumn(name = "CountryCode", foreignKey = @ForeignKey(name = "countryLanguage_ibfk_1"))
    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }

    @Basic
    @Column(name = "IsOfficial")
    public String getIsOfficial() {
        return isOfficial;
    }

    public void setIsOfficial(String isOfficial) {
        this.isOfficial = isOfficial;
    }

    @Basic
    @Column(name = "Percentage")
    public Double getPercentage() {
        return percentage;
    }

    public void setPercentage(Double percentage) {
        this.percentage = percentage;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Countrylanguage that = (Countrylanguage) o;
        return Objects.equals(language, that.language) &&
                Objects.equals(country, that.country) &&
                Objects.equals(isOfficial, that.isOfficial) &&
                Objects.equals(percentage, that.percentage);
    }

    @Override
    public String toString() {
        return "Countrylanguage{" +
                "language='" + language + '\'' +
                ", country=" + country.getName() +
                ", isOfficial='" + isOfficial + '\'' +
                ", percentage=" + percentage +
                '}';
    }

    @Override
    public int hashCode() {
        return Objects.hash(language, country, isOfficial, percentage);
    }
}

HQL

HQL是Hibernate的数据库查询语言,看名字可以知道这种查询语言和SQL类似。其实呢,这种查询语言,其实就是SQL中把表名和列名换成了实体类名和属性名。而且如果使用IDEA这样的智能集成开发环境,还会贴心的把SQL和HQL等查询语言高亮显示,特别方便。

首先我们需要创建一个Session,然后使用session.createQuery方法创建一个Query对象,然后调用query.list方法获取查询结果。这是一个简单的例子,演示了一下HQL的基本用法。如果需要更详细的用法还是查阅相关资料更好。

代码语言:javascript
复制
    @Test
    public void test() {
        try (Session session = factory.openSession()) {
            //查询所有国家
            List<Country> countries = session.createQuery("from Country", Country.class).list();
            //查询c开头的所有国家
            List<Country> countriesStartWithC = session.createQuery("from Country c where c.name like 'c%'", Country.class).list();
            //countries.forEach(country -> logger.info(country.toString()));
            countriesStartWithC.forEach(country -> logger.info(country.toString()));
            //查询中国的国家代码
            List<String> countryCodes = session.createQuery("select c.code from Country c where c.name='China'", String.class).list();
            countryCodes.forEach(c -> logger.info(c));
            //查询中国的所有城市
            List<City> cities = session.createQuery("from City c where c.country.name='China'", City.class).list();
            cities.forEach(c -> logger.info(c.toString()));
        }

    }

Criteria

Criteria是Hibernate提供的另外一种查询语言。Criteria有两个版本,org.hibernate.Criteria属于旧版本的,虽然还没有标记为过时,Hibernate官方已经不推荐我们使用这种了。相应的,我们应该使用javax.persistence.criteria.CriteriaBuilder接口来创建和使用查询。

首先需要调用getCriteriaBuilder方法生成一个CriteriaBuilder。然后使用Builder的createQuery方法创建一个查询。Root对象代表查询的根,也就是要查询的表,然后可以使用查询对象提供的各种方法来查询我们要的数据。详细的使用方法还是需要查阅文档。

代码语言:javascript
复制
    @Test
    public void testCriteria() {
        try (Session session = factory.openSession()) {
            //查询人口最少的20个城市
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<City> query = builder.createQuery(City.class);
            Root<City> root = query.from(City.class);
            query.select(root);
            query.orderBy(builder.asc(root.get("population")));
            List<City> cities = session.createQuery(query).setMaxResults(20).list();
            cities.forEach(city -> logger.info(city.toString()));
        }
    }

Native SQL

除了使用上面所说的查询语言之外,还可以直接使用SQL查询数据。调用Session.createNativeQuery即可创建一个SQL查询。需要注意返回的结果是一个List

代码语言:javascript
复制
    @Test
    public void testSQL() {
        try (Session session = factory.openSession()) {
            //东亚所有国家和地区
            NativeQuery query = session.createNativeQuery("select code,name,population from country where Region='Eastern Asia'");
            List<Object[]> countries = query.getResultList();
            for (Object[] country : countries) {
                String code = (String) country[0];
                String name = (String) country[1];
                int population = (int) country[2];
                logger.info("Code:{} Name:{} Population:{}", code, name, population);
            }
        }
    }

以上就是Hibernate提供的几种查询方式。我这里只做了一点简单介绍,详细的使用方法还是需要查看更详细的资料。不过这些方法基本大同小异,只要熟悉SQL数据库的查询语言,学会这几种查询方法也很简单。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-01-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建实体类
  • HQL
  • Criteria
  • Native SQL
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档