实体类
@Entity --Specifies that the class is an entity. This annotation is applied to the entity class.
@Table(name = "b_relation") --Specifies the primary table for the annotated entity. Additional tables may be specified using SecondaryTable or SecondaryTables annotation.
@Id --The mapped column for the primary key of the entity is assumed to be the primary key of the primary table. If no Column annotation is specified, the primary key column name is assumed to be the name of the primary key property or field.
@GeneratedValue(strategy = GenerationType.AUTO) --Provides for the specification of generation strategies for the values of primary keys.
javax.persistence.GenerationType --Defines the types of primary key generation strategies.
GenerationType.AUTO
GenerationType.IDENTITY
GenerationType.SEQUENCE
GenerationType.TABLE
@Column(name = "id", unique = true, nullable = false, precision = StaticConstant.EIGHTEEN)
SQL执行接口UserRespository
在服务实现中直接调用其方法
继承JpaRepository<User, String>或CrudRepository<User, String>
@Modifying --Indicates a method should be regarded as modifying query.
@Query --Annotation to declare finder queries directly on repository methods.
value ="sql语句", nativeQuery = true 是否为原生sql
@Query(value = "select count(1) from b_relation a where a.id = ?1 and a.num = ?2", nativeQuery = true)
BigInteger queryInfo(String id, String num);
@Modifying
@Query(value = "delete from b_relation where id = ?1", nativeQuery = true)
void delInfo(String userid);
配置文件 persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="test-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:/comp/env/jdbc/test</non-jta-data-source>
<class>com.wxx.entity.User</class>
<properties>
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.use_sql_comments" value="false" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
</properties>
</persistence-unit>
</persistence>
本文介绍了使用Java Persistence API (JPA) 和 Hibernate 进行实体映射的方法,包括实体类定义、注解使用、SQL执行接口及配置文件的设置。探讨了不同主键生成策略的应用场景,并展示了如何通过Repository接口实现数据的增删查改操作。
746

被折叠的 条评论
为什么被折叠?



