jpa
配置
hibernate-configuration-3.0.dtd hibernate.cfg.xml
@Entity(name)、@Id、@GeneratedValue
死格式
Configuration().configure()、SessionFactory
Session
createQuery( class ).list()、get( class , id )
save( obj )、update( obj )、saveOrUpdate()、delete ( obj )
close()、commit()、
日志
log4j.logger.org.hibernate.tool.hbm2ddl=all
依赖
org.hibernate
hibernate-core
5.3.10.Final
mysql
mysql-connector-java
5.1.47
项目结构里面添加hibernate支持
然后在persistence里面
选择项目后新建-Session Factory-然后选择项目的resources目录创建一个hibernate.cfg.xml文件
在文件中写好
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.driver_class">org.git.mm.mysql.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>换数据库时改方言,驱动,数据库地址就可以了,方便换
<property name="hibernate.hbm2ddl.auto">update</property>
hibernate.hbm2ddl.auto
validate、update、create、create-drop
使用slf4j日志时要配置
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="com.yvdedu.hibernate.po.User"/>
hibernate创建模型po
类上加注释@Entity
id加@Id@GenerateValue(strategy = GenerationType.IDENTITY)id的生成方式是自动递增
使用时用
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory();
try{
Session session = factory.openSession();
try{
Transaction bt= session.beginTransaction();事物
保存语句session.save(new User("a","a");
查询语句
1.
List<User> users = session.createQuery("frome User where account='a'").list();
List<User> users = session.createQuery("frome User where account;account")
.setParameter("account","a")
.list();
System.out.println(users);
2. System.out.println(session.get(User.class,"2");查询id为2的数据
修改语句
User user= session.get(User.class,2);
user.setAccount("acs");
user.setPassword("asd");
删除语句
session.delete(new User(3));
bt.commit();事物提交
}finally{
session.close();
}
}
}finally{
factory.close();
}
hibernate的持久化链接
System.setProperty("hibernate.dialect.storage_engine","innodb");
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
SchemaExport se = new SchemaExport();
se.setFormat(true);
se.create(TargetTypeHelper.parseCommandLineOptions("stdout"), metadata);
serviceRegistry.close();加这一条就只有sql显示不会执行到数据库去
属性
@Basic基础映射数据(默认)、@Transient(不需要保存的数据)、@Temporal(日期可改变数据库类型TemporalType.TIME三种)
时间java中类型只有private Date date;数据库中为datetime
数据验证规范
@Column(length=20,name="..."别名,nullable=false,unique=true)
name、unique、updatable、length、nullable
表
@Table(name="table_user",uniqueConstraints=@UniqueConstraint(columnName={"account","password"}联合唯一键))
System.setProperty("hibernate.dialect.storage_engine","innodb");
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
SessionjFactory factory=metadata.buildSessionFactory();
Session session = factory.openSession();
User user = new User();
user.setName("adf");
Account account = new Account();
account.setAccont("aa");
account.setUser(user);
user.setAccount(accont);
Transaction tr = session.beginTransaction();
session.save(user);
session.save(account);
tr.commit();
session.close();
factory.close();
serviceRegistry.close();
@OneToOne(cascade = CascadeType.ALL关联维护存储)外键关联
在account类上加一个user属性写上@OneToOne这个维护关系@JoinColumn(unique=ture)链接唯一
在user类上加一个account类写上@OneToOne(mapperBy="user")这个不维护关系
mappedBy、unique配置
关联维护存储
对象持有关联引用、cascade
role类@OneToMany(mapperBy="role")、 user类@ManyToOne
@JoinColumn
name
@ManyToMany任意一边写mapperBy
@JoinTable(joinColumns = @joinColumn(name="user_id"),inverseJoinColumns = @JoinColumn(name = "role_id"))
Session
createQuery()优先选择、createCriteria()面对对象的查询比较难用、createSQLQuery()谨慎使用
Query
setXX()、命名参数、executeUpdate()数据更新、list()数组、uniqueResult()一个对象的结果
分页setFirstResult()从第几个数开始查、setMaxResults()查几条
HQL Base
select …… from …… where
update 模型名称 as …… set …… where
session.createQuery("update user set name=:name where id=:id")
.setParameter("name","a")
.setParameter("id",2)
.executeUpdate();
session.createQuery(update user set name=?1 where id=?2)
.setParameter(1,"a")
.setParameter(2,2)
.executeUpdate();
insert into class(properties) select …… from实际上就是复制表
查询一个数据的时候不用list()用uniqueResult();
select
new list()、new class()、new map( value as key )
查询数组中包含数组时.createQuery("select new list(id,name) from User").list();.createQuery("select new user(id,name)要有构造方法 from User").list();
join:left、right、full、m2m join
from user as u join u.roles
select newlist(id,case when id>1 then '大' else '小' end)