后端开发者的福音,不用写一行javascript和CSS轻松实现CRUD

vaadin介绍

今天在github发现一个开源库vaadin,vaadin主要特点:
1.不用前后端分离开发应用
2.整个应用使用java实现(包括前端所有功能)
3.包含大量的UI组件
详细的功能介绍可以去git上查看

https://github.com/tangyajun/platform.git

使用vaadin实现CRUD

1. 创建spring-boot项目

新建一个spring-boot项目crud-ui-with-vaadin
在这里插入图片描述
选择Spring-Data-JPA和H2 DataBase
在这里插入图片描述
点击finish
在这里插入图片描述

2.导入vaadin
<properties>
    <java.version>1.8</java.version>
    <vaadin.version>14.0.9</vaadin.version>
</properties>
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
3. 创建domain对象和repository

创建domain对象
使用@Entity注解标注

@Entity
@Getter
@Setter
public class Customer {
	@Id
	@GeneratedValue
	private Long id;
	private String name;
	private Integer gender;
	private Integer age;
	private String phone;
	private String email;
	private String address;
	public Customer() {

	}
	public Customer(String name,int gender,int age,String phone,
	                String email,String address) {
		this.name=name;
		this.gender=gender;
		this.age=age;
		this.phone=phone;
		this.email=email;
		this.address=address;
	}
	@Override
	public String toString() {
		return String.format("Customer[id=%d,name='%s',gender=%d,age=%d,phone='%s',email='%s',address='%s'",
				id,name,gender,age,phone,email,address);
	}
}

创建repository

public interface CustomerRepository extends JpaRepository<Customer,Long> {
	/**
	 * 根据姓名查询
	 * @param name 
	 * @return
	 */
	List<Customer> findByNameStartingWithIgnoreCase(String name);
}
4. 创建视图类
实现查询列表

1.创建查询视图类

@Route
public class MainView extends VerticalLayout {
    private final CustomerRepository repo;
	final Grid<Customer> grid;
	final TextField filter;
	private final Button addNewBtn;
	public MainView(CustomerRepository repo) {
		this.repo = repo;
		// 创建客户列表grid
		this.grid = new Grid<>(Customer.class);
		// 创建查询过滤文本框
		this.filter = new TextField();
		// 实例化新建按钮
		this.addNewBtn = new Button("新建", VaadinIcon.PLUS.create());
		HorizontalLayout actions = new HorizontalLayout(filter, addNewBtn);
		// 添加到视图
		add(actions, grid);
        /**
        * 设置grid 高度,列名
        */
		grid.setHeight("300px");
		grid.setColumns("id", "name", "gender","age","phone","email","address");
		grid.getColumnByKey("id").setWidth("50px").setFlexGrow(0);
		filter.setPlaceholder("请输入客户姓名");

		// 设置文本过滤器事件模式(内容改变触发)
		filter.setValueChangeMode(ValueChangeMode.EAGER);
		// 添加事件监听
		filter.addValueChangeListener(e -> listCustomers(e.getValue()));
	}
}

2.实现查询过滤方法

void listCustomers(String filterText) {
		if (StringUtils.isEmpty(filterText)) {
			grid.setItems(repo.findAll());
		}
		else {
		// 调用repository查询数据
		 grid.setItems(repo.findByNameStartingWithIgnoreCase(filterText));
		}
	}
实现增删改功能

创建编辑视图类,使用form表单布局

@SpringComponent
@UIScope
public class CustomerEditor extends FormLayout implements KeyNotifier {
	private final CustomerRepository repository;
	private Customer customer;
	/**
	* 定义编辑的文本对象(等同<input type="text" />)
	*/
	TextField name = new TextField(" name");
	TextField gender = new TextField("gender");
	TextField age=new TextField("age");
	TextField phone=new TextField("");
	TextField email=new TextField("email");
	TextField address=new TextField("address");
    /**
    * 定义操作按钮(等同<input type="button"/>)
    */
    Button save = new Button("保存", VaadinIcon.CHECK.create());
	Button cancel = new Button("取消");
	Button delete = new Button("删除", VaadinIcon.TRASH.create());
	HorizontalLayout actions = new HorizontalLayout(save, cancel, delete);
	/**
	* 定义binder
	*/
	Binder<Customer> binder = new Binder<>(Customer.class);
	/**
	* 定义
	*/
	private ChangeHandler changeHandler;
    @Autowired
	public CustomerEditor(CustomerRepository repository) {
		this.repository = repository;
		/*
		*绑定domain对象中的属性
		* Integer类型需要使用StringToIntegerConverter转换
		*/ 
		binder.forField(age).withConverter(new StringToIntegerConverter(""))
		.bind(Customer::getAge,Customer::setAge);
		binder.forField(gender).withConverter(new StringToIntegerConverter(""))
		.bind(Customer::getGender,Customer::setGender);
	
		add(name, gender,age,phone,email,address, actions);

		// 绑定实例属性
		binder.bindInstanceFields(this);
		
		save.getElement().getThemeList().add("primary");
		delete.getElement().getThemeList().add("error");
		/**
		* 添加按钮点击事件
		*/
		addKeyPressListener(Key.ENTER, e -> save());

		// 添加按钮单机监听事件
		save.addClickListener(e -> save());
		delete.addClickListener(e -> delete());
		cancel.addClickListener(e -> editCustomer(customer));
		// 保存后设置为不可见
		setVisible(false);
	}
}

实现删除和保存

void delete() {
		repository.delete(customer);
		changeHandler.onChange();
	}

	void save() {
		repository.save(customer);
		changeHandler.onChange();
	}
加载查询列表数据
@Bean
	public CommandLineRunner loadData(CustomerRepository repository) {
		return (args) -> {
			repository.save(new Customer("Jack", 1,20,"1861111121","[email protected]","广东"));
			repository.save(new Customer("Chloe", 0,28,"11223232","[email protected]","湖南"));
			repository.save(new Customer("Kim", 1,30,"15810911761","[email protected]","山东"));
			repository.save(new Customer("David", 1,22,"13693669002","Palmer","河北"));
			repository.save(new Customer("Michelle", 1,23,"170111121","Dessler","北京"));

			// fetch all customers
			log.info("Customers found with findAll():");
			log.info("-------------------------------");
			for (Customer customer : repository.findAll()) {
				log.info(customer.toString());
			}
			log.info("");
			Customer customer = repository.findById(1L).get();
			log.info("Customer found with findOne(1L):");
			log.info("--------------------------------");
			log.info(customer.toString());
			log.info("");

			log.info("Customer found with findByLastNameStartsWithIgnoreCase('Chloe'):");
			log.info("--------------------------------------------");
			for (Customer bauer : repository
					.findByNameStartingWithIgnoreCase("Chloe")) {
				log.info(bauer.toString());
			}
			log.info("");
		};
	}
5. 启动服务查看效果

客户列表
在这里插入图片描述
过滤客户列表
在这里插入图片描述
新增客户
在这里插入图片描述
在这里插入图片描述
删除客户,选择要删除的客户点击删除
在这里插入图片描述
在这里插入图片描述
全部使用java实现的CRUD功能到这就结束了,源码下载
https://github.com/tangyajun/crud-ui-with-vaadin.git

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章